Statement invalid while rendering json in Rails

60 Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

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.