默认值多态关联不起作用?

时间:2014-11-05 20:47:26

标签: ruby-on-rails ruby-on-rails-4 default-value polymorphic-associations

我有prototypical polymorphic model

的修改版本
class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true

  before_save :default_value

  private

  def default_value
    Rails.logger.debug("*** Setting default value ***")
    # Set default values here
  end
end

class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

class Product < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

我已尝试将Picture模型的默认值设为suggested in an answer to a similar question

问题是,在保存default_valueEmployee时,不会调用Product方法。

我可以确认db已正确设置,因为我在rails console中运行了它:

emp = Employee.create() # Creating Employee.id == 1
emp.pictures.count # == 0
Picture.create(imageable_id: 1, imageable_type: "Employee") # Here, setting defaults works fine
Employee.find(1).pictures.count # == 1

所以问题是:当我保存default_valueEmployee时,为什么不会Product被调用?

1 个答案:

答案 0 :(得分:1)

回调的工作方式与consoleserver相同。只有在保存对象时才会触发此回调。

如果保存Employee,则只有在子项中更改了任何属性时,才会更改保存时子项的值。例如:

emp = Employee.first
emp.pictures.first.foo = "bar" # assuming that you have a column foo in pictures table
emp.save # will save the picture and trigger the callback `before_save`

但如果您有以下情况,则不会保存图片:

emp = Employee.first
emp.save # will save only emp

如果由于某种原因需要保存所有图片,可以执行以下操作:

class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
  before_save :default_value

  def default_value
    self.pictures.update_all(foo: "bar")
  end
end