在某些情况下,ActiveRecord has_one关系不会返回

时间:2009-12-30 23:38:32

标签: ruby-on-rails activerecord one-to-one belongs-to has-one

给出三个彼此嵌套的模型。如果我创建顶级对象和build_ *其他子对象,我可以通过原始实例上save()之前和之后的关系检索所有子对象。但是,如果我尝试在find(:id)之后检索第二级嵌套对象,则原始父级将失败。但是,我可以检索第一级嵌套对象。这通常发生在控制器中,但我将在下面的控制台输出中进行说明。

我在俯瞰什么?

提前致谢!
〜JPV

>> l = Lead.new :buyer_name => 'Kim Possible', :email => 'kim@possible.com', :phone => '7131231234'
>> l.build_buyer
>> l.buyer.name = 'kim buyer'
>> l.buyer
>> l.buyer.build_contact_detail
>> l.buyer.contact_detail.email = "kim-contact-detail@possible.com"
>> l.save #returns true
>> l.buyer #THIS WORKS
=> #<Buyer id: 1, name: "kim buyer", lead_id: 1>
>> l.buyer.contact_detail #THIS WORKS
=> #<ContactDetail id: 1, company_id: nil, buyer_id: 1, email: nil, address_line_1: nil, address_line_2: nil, city: nil, state: nil, postal_code: nil>
>> l2 = Lead.find(1)
=> #<Lead id: 1, company_id: nil, buyer_id: nil, public_lead_id: nil, buyer_name: "Kim Possible", company_name: nil, email: "kim@possible.com", phone: "7131231234">
>> l2.buyer #THIS WORKS AS EXPECTED
=> #<Buyer id: 1, name: "kim buyer", lead_id: 1>
>> l2.buyer.contact_detail #THIS BREAKS
=> nil

以下所有样板材料:

class Lead
  has_one :buyer
  #...
end

class Buyer
  has_one :contact_detail
  belongs_to :lead
  #...
end

class ContactDetail
  belongs_to :buyer
  #...
end

适当的外键位于每个“belongs_to”类中。

class CreateBuyers < ActiveRecord::Migration
  def self.up
    create_table :buyers do |t|
      t.string :name
      t.integer :lead_id
...

class CreateContactDetails < ActiveRecord::Migration
  def self.up
    create_table :contact_details do |t|
      t.integer :buyer_id

2 个答案:

答案 0 :(得分:1)

我认为你可能会被绊倒,因为你期望对象急于加载嵌套的子对象。通常,您必须在find中明确指定它。尝试添加:include =&gt; [:借款人,{:借款人=&gt; :contact_detail}]到find的选项,看看是否有效。

答案 1 :(得分:0)

如果你这样做,这是否有效...

l.buyer.name = 'kim buyer'
l.save
l.buyer.build_contact_detail
...

如果是这样,这可能是一个跟踪错误,因为ContactDetail对象在创建时并不真正知道其父亲是谁。