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