ruby on rails - Default value polymorphic associations doesn't work? -
ruby on rails - Default value polymorphic associations doesn't work? -
i have modified version of prototypical polymorphic model
class image < 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
here i've tried set default values picture
model, suggested in reply similar question.
problem is, default_value
method isn't called when employee
or product
beingness saved.
i can confirm db set correctly, because ran in 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
so question is: why doesn't default_value
called when save employee
or product
?
callbacks work same way console
or server
. callback triggered if object beingness saved.
if save employee
alter value of kid on save, if attribute changed in child. example:
emp = employee.first emp.pictures.first.foo = "bar" # assuming have column foo in pictures table emp.save # save image , trigger callback `before_save`
but if have next scenario, pictures not saved:
emp = employee.first emp.save # save emp
if need save pictures reason, can following:
class employee < activerecord::base has_many :pictures, as: :imageable before_save :default_value def default_value self.pictures.update_all(foo: "bar") end end
ruby-on-rails ruby-on-rails-4 default-value polymorphic-associations
Comments
Post a Comment