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