Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make associations work in built and unsaved objects?

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
like image 822
CodeOverload Avatar asked Nov 11 '13 11:11

CodeOverload


2 Answers

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)
like image 194
Daniel Rikowski Avatar answered Nov 02 '22 13:11

Daniel Rikowski


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.

like image 3
Graham Conzett Avatar answered Nov 02 '22 13:11

Graham Conzett