开发者

Getting ActiveRecord association id in callback function

开发者 https://www.devze.com 2023-04-02 15:20 出处:网络
I have two associated m开发者_如何学JAVAodels, employee and doctor: class Employee < ActiveRecord::Base

I have two associated m开发者_如何学JAVAodels, employee and doctor:

class Employee < ActiveRecord::Base
  has_one :doctor, :dependent => :destroy
  ...
end

class Doctor < ActiveRecord::Base
  belongs_to :employee
end

When the doctor has already been created and saved.

I want to get access to doctors id in employees after_save callback:

class Employee < ActiveRecord::Base
  ...
  after_save :save_picture
  ...
  private
  def save_picture
    if doctor
      file_name = 'doctor_' + doctor.id.to_s + '.jpg'
      ...
    end
  end
end

I can get access to any doctors method and any of them works fine, but "id" - it returns "nil".

What am I doing wrong?


Does your Doctor model have an id accessor?

Try doctor_id instead of doctor.id, one database query less :)


I found out where my mistake was:

I had a bad accessor in Employee class

class Employee < ActiveRecord::Base
  ...
  def is_doctor= val
    create_doctor if val == '1'
  end
  ...
end

It was trying to create a new doctor, but it fault on update action. After that, doctors id attribute in 'self'-object was empty.

The solution was to place association manipulations to another after_save callback:

class Employee < ActiveRecord::Base
  has_one :doctor, :dependent => :destroy
  after_save :save_roles
  after_save :save_picture
  ...
  def is_doctor= val
    @doc = true if val == '1'
  end

  private

  def save_roles
    if doctor
      doctor.destroy unless @doc
    else
      create_doctor if @doc
    end
    @doc = nil
  end

  def save_picture
    if doctor
      file_name = 'doctor_' + doctor.id.to_s + '.jpg'
      ...
    end
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消