Delegation: id when creating a new instance

I have three models:

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

      

This works great and I can call dog.employee_id in my opinion. However, if I want to create a new instance in RailsAdmin (not while editing an existing object), I get this error:

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 is true, and delegation for other attributes works fine. What is the problem and how can I fix it?

+3


source to share


1 answer


You don't need a delegate to access dog.employee_id.



The belongs_to relationship already assumes Dog will hold the foreign key to Employee and creates an employee_id attribute.

+3


source







All Articles