ruby-on-railsruby-on-rails-5rails-apiruby-on-rails-5.2railsapps

Statement invalid while rendering json in Rails


for my snippet below for rendering the json

def show
   @product = Product.find(params[:id])
      render json: @product.to_json(:include => { :items => { :only => [:id, 
:description] }}) 
end

While rendering the json for has many attributes model I am getting invalid statement as follows:

(Mysql2::Error: Unknown column 'items.product_id' in 'where clause': SELECT `items`.* FROM `items` WHERE `items`.`product_id` = 1):

While I have a column called products_id for the foreign key instead of product_id. I need to throw statement as products_id without changing the column name in database.


Solution

  • In your Product model you should have something like has_many :items. This line creates an association with default foreign key product_id. To change foreign key you need to change this line to has_many :items, foreign_key: :products_id.