我的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。
问题是,当保存Employee
或Product
时,不会调用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
得到当我保存的Employee
或Product
叫?
你是什么意思的“保存'员工'或'产品'“?根据你的例子,我没有看到为什么这两个类会继承'Picture'的方法。你想做什么? – ptd 2014-11-05 21:10:41
感谢您的评论ptd!在我看来,我希望这种设置应该更像是一种“继承”,但正如我在接受的答案的评论中写到的,我现在明白了为什么它不能做到我想要的。 – conciliator 2014-11-06 10:33:59