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.
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? 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.
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.
You could use :inverse_of to set it. Read more about it here.
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