开发者

Rails - ActiveRecord - How does it populate objects and relationships?

开发者 https://www.devze.com 2023-04-05 00:50 出处:网络
I noticed that by programmatically traversing from a parent object to a child object, and then back again, that the parent object I get back is not the same as the original one.

I noticed that by programmatically traversing from a parent object to a child object, and then back again, that the parent object I get back is not the same as the original one.

For example:

Parent class: Car

Child class: Seat

A car has many seats

puts(@car.to_s) => a memory address

puts(@car.seats.first.car.to_s) => totally different address

I noticed this because I recently added a new string field to Car through a migration, and by trying to read it by traversing the relationship back from seat, that field was always nil! However, adding the field to the scaffold view and checking the database, the new field and values are there.

It's wei开发者_StackOverflow中文版rd because all the old fields are available. It's only the new one that is not. For what it's worth, the second-to-last field is also a string.

What is going on under the hood? What do I need to do? Thanks!


Let's suppose by Parent and Child class, you mean Car has_many Seats. You could try to tell ActiveRecord that one relation is the inverse of the other.

class Car < ActiveRecord::Base
    has_many :seats, :inverse_of => :car
end

class Seat < ActiveRecord::Base
    belongs_to :car, :inverse_of => :seats
end

So, to quote the Rails documentation, doing so will let you things like that :

d = Dungeon.first
t = d.traps.first
d.level == t.dungeon.level # => true
d.level = 10
d.level == t.dungeon.level # => true
0

精彩评论

暂无评论...
验证码 换一张
取 消