I am relatively new to rails. I am reading AWDWR 7.
I am at page 120, I have some questions and having some problems.
Questions:
In line_item model we create a relationship to product and cart models. Do we need a n x m relationship between product and cart models? Because of that we create the line_item model?
Also inside the product and cart models we have has_many :line_items. Where is these relationships inside our schema.rb? I don’t see any sql relationship? If we don’t have a sql relationship is it good way to create relationships in ruby?
Need help code debugging:
I think I am having some problem. inside the line_items_controller.rb in the create method at @line_item = @cart.line_items.build(product: product) it gives me error. Saying : ActiveModel::MissingAttributeError in LineItemsController#create
can’t write unknown attribute product_id. Any helps solving this problem
In line_item model we create a relationship to product and cart models. Do we need a n x m relationship between product and cart models? Because of that we create the line_item model?
Yes.
Also inside the product and cart models we have has_many :line_items. Where is these relationships inside our schema.rb? I don’t see any sql relationship? If we don’t have a sql relationship is it good way to create relationships in ruby?
The relationships are foreign keys defined in the line item, specifically product_id and cart_id.
What’s going on here is that belongs_to matches a foreign key defined on this model/table, and both has_one and has_many matches a foreign key defined on the referenced model/table.
If you are familiar with SQL, try running the command bin/rails console. And within the console type the following two commands:
product = Product.last
product.line_items
As you type these commands, you will see the SQL that was evaluated.
I think I am having some problem. inside the line_items_controller.rb in the create method at @line_item = @cart.line_items.build(product: product) it gives me error. Saying : ActiveModel::MissingAttributeError in LineItemsController#create
can’t write unknown attribute product_id. Any helps solving this problem
If you have has_one, what Rails will attempt to do is to update an attribute named line_item_id in the Product model/products table, and not find any such attribute defined.