Let's say I have something like:
@order = Order.new(status: :pending)
@item = @order.items.build(title: "Shirt")
When I try to call @item.order
, I get an error not found, I guess it's because it's still unsaved to the DB, but how can make it point to the built object without saving any of the objects?
@item.order # Not Found - Tries to fetch from the DB
To make this work you have to tell the order
association of your item model that it is the inverse of your items
association or you order model and vice versa:
Like this:
class Item < ActiveRecord::Base
belongs_to :order, inverse_of: :items
end
class Order < ActiveRecord::Base
has_many :items, inverse_of: :order
end
That way your associations will be set up correctly even before saving to the database.
EDIT: If you don't want this you can always assign the association explicitly:
@item = @order.items.build(title: "Shirt")
@item.order = @order
or in one line:
@item = @order.items.build(title: "Shirt", order: @order)
I tested this in Rails 4.0.1 and it looks like using inverse_of
is no longer needed as the associations are inferred properly. It was addressed in this commit: https://github.com/rails/rails/pull/9522
It is worth noting that there is still no solution for has_many through:
relationships at this time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With