0

我的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

问题是,当保存EmployeeProduct时,不会调用default_value方法。

我可以证实,该数据库设置正确,因为我跑这在轨控制台:

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_value得到当我保存的EmployeeProduct叫?

+0

你是什么意思的“保存'员工'或'产品'“?根据你的例子,我没有看到为什么这两个类会继承'Picture'的方法。你想做什么? – ptd 2014-11-05 21:10:41

+0

感谢您的评论ptd!在我看来,我希望这种设置应该更像是一种“继承”,但正如我在接受的答案的评论中写到的,我现在明白了为什么它不能做到我想要的。 – conciliator 2014-11-06 10:33:59

回答

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 
+0

谢谢mohameddiaa27。我意识到我希望'Employee'和'Product''继承“(在行为意义上)'Picture's方法,但这不可能奏效。如果一个人多次保存“员工”会发生什么?是否应该在每个保存的“图片”中创建一个新记录?这个行为对我来说是有道理的。谢谢你的努力! :) – conciliator 2014-11-06 10:31:02