I’m attempting to retrieve information from the IEX Trading API through RapidAPI within my Rails application. I’ve set up a search form intended to use the entered query to fetch the data, but I encounter the following error message, despite it functioning correctly in the console with the query set as “FB”:
method ‘fetch_company_info’ not defined for “FB”:String
stock.rb
class Equity < ApplicationRecord
validates :symbol, uniqueness: true
def self.fetch_company_info
response = Unirest.get "https://investors-exchange-iex-trading.p.rapidapi.com/stock/#{@equity}/company",
headers: {
"X-RapidAPI-Key" => [xxx]
}
company_data = response.body
@equity = Equity.create(
symbol: company_data["symbol"],
name: company_data["companyName"],
exchange: company_data["Exchange"],
sector: company_data["industry"],
website: company_data["website"],
description: company_data["description"]
)
end
end
equities_controller.rb
class EquitiesController < ApplicationController
def search
end
def results
@equity = params[:equity]
@equity.fetch_company_info unless @equity.nil?
end
end
I appreciate any assistance you can provide!
In addition to the helpful suggestion by CreatingStone, ensuring that the code functions correctly involves addressing a few more points:
- Use Instance Methods Appropriately: The method
fetch_company_info
should be a class method because it is creating a new Equity
object. Therefore, it should not rely on instance variables. Additionally, always ensure that your APIs are correctly authenticated by substituting placeholders like [xxx]
with actual API keys.
- Refactor and Test: It’s important to refactor the code and test it thoroughly to ensure it functions properly across different scenarios. For instance, te stting your method with various input symbols can reveal potential edge cases, such as handling non-existent stocks.
- Improve Error Handling: Adding error handling for the API requests would be beneficial. For instance, network errors or invalid API responses can be gracefully managed by implementing error handling like so:
def self.fetch_company_info(symbol)
begin
response = Unirest.get "https://investors-exchange-iex-trading.p.rapidapi.com/stock/#{symbol}/company",
headers: {
"X-RapidAPI-Key" => '[your_api_key]'
}
raise "Fetch Error" unless response.code == 200
company_data = response.body
Equity.create(
symbol: company_data["symbol"],
name: company_data["companyName"],
exchange: company_data["exchange"],
sector: company_data["industry"],
website: company_data["website"],
description: company_data["description"]
)
rescue => e
Rails.logger.error "Error fetching company info for #{symbol}: #{e.message}"
end
end
By applying these adjustments, your application should be more robust when interacting with external APIs such as IEX Trading through RapidAPI. This will allow for better management of API responses and system stability.
To resolve the issue you’re experiencing, you need to adjust how you're calling the fetch_company_info
method. The error arises because the method is called on a string, rather than on the class itself. Follow these steps:
- Update the Controller: Modify the
results
method in your EquitiesController
to pass the symbol to the class method correctly:
class EquitiesController < ApplicationController
def results
symbol = params[:equity]
Equity.fetch_company_info(symbol) unless symbol.nil?
end
end
- Modify the Method: The
fetch_company_info
should accept a symbol as an argument, not rely on instance variables:
def self.fetch_company_info(symbol)
response = Unirest.get "https://investors-exchange-iex-trading.p.rapidapi.com/stock/#{symbol}/company",
headers: {
"X-RapidAPI-Key" => '[your_api_key]'
}
company_data = response.body
if response.code == 200
Equity.create(
symbol: company_data["symbol"],
name: company_data["companyName"],
exchange: company_data["exchange"],
sector: company_data["industry"],
website: company_data["website"],
description: company_data["description"]
)
else
Rails.logger.error "Failed to fetch data for #{symbol}"
end
end
By making these changes, you ensure that your method operates correctly as a class-level method, fetches company info efficiently, and handles potential API interaction issues effectively. This optimized approach should resolve the error and improve overall robustness.