我有三种型号:
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.employe_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,其他属性的委派工作正常。问题出在哪里?我该如何解决?
您不需要委派即可访问dog.employe_id.
belongs_to关系已经暗示Dog将持有Employee的外键,并创建Employee_id属性。