Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how can I retrieve the object on a belongs_to association, without going through the database?

Consider the following setup:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

And this console session:

>> p = Parent.find 41
>> p.some_attr = 'some_value'
>> c = p.children.build
>> c.parent

By watching my log files, I can see that c.parent is querying the db for the parent object. I want instead to access the existing in-memory object (p), because I need access to the parent's some_attr value, which is not yet stored in the database. Is there any way of doing this? c.parent(force_reload=false) doesn't get me there.

like image 321
KenB Avatar asked Jun 30 '10 19:06

KenB


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


1 Answers

You could use :inverse_of to set it. Read more about it here.

like image 199
YonahW Avatar answered Oct 18 '22 04:10

YonahW