gpt4 book ai didi

ruby-on-rails - 内存关联引用损坏 : Reference parent object before save returns nil

转载 作者:行者123 更新时间:2023-12-01 11:45:24 24 4
gpt4 key购买 nike

我有以下两个模型:

class Seller < ActiveRecord::Base
has_many :cars, :dependent => :destroy
end

class Car < ActiveRecord::Base
belongs_to :seller
end

现在我需要能够在对象保存到数据库之前从汽车中引用卖家,这目前不起作用:

seller = Seller.new
=> #<Seller id: nil, name: nil, created_at: nil, updated_at: nil>
seller.cars.build(:brand => 'Audi', :model_name => 'A4')
=> #<Car id: nil, brand: 'Audi', model_name: 'A4', created_at: nil, updated_at: nil>

现在协会从卖方开始工作,而不是从汽车方面工作:

car = seller.cars.first
=> #<Car id: nil, brand: 'Audi', model_name: 'A4', created_at: nil, updated_at: nil>
car.seller
=> nil

如何让关联正常工作?

附言。如前所述,如果我将对象保存到数据库中,那么引用将按其应有的方式工作。

最佳答案

好吧,我似乎自己找到了答案:

我必须在卖家上指定 :inverse_of 然后它才有效:

class Seller < ActiveRecord::Base
has_many :cars, :inverse_of => :seller, :dependent => :destroy
end

关于ruby-on-rails - 内存关联引用损坏 : Reference parent object before save returns nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15852269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com