委托:创建新实例时的id

时间:2013-02-05 08:30:20

标签: ruby ruby-on-rails-3 rails-admin

我有三种模式:

class Company < ActiveRecord::Base
  has_many :employees
  has_many :dogs, :through => :employees
end

class Employee < ActiveRescord::Base
  belongs_to :company
  has_many :dogs
end

class Dog < ActiveRecord::Base
  belongs_to :employee

  delegate :id, :to => :employee, :prefix => true, :allow_nil => true
end

这完全正常,我可以在我看来调用dog.employee_id。但是,如果我想在RailsAdmin中创建一个新实例(而不是在编辑现有对象时),我会收到此错误:

RuntimeError at /dog/new
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

:allow_nil设置为true,其他属性的委托可以正常工作。有什么问题,我该如何解决?

1 个答案:

答案 0 :(得分:3)

您不需要委托就可以访问dog.employee_id。

belongs_to关系已经暗示Dog会将外键保存到Employee并创建employee_id属性。