Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why before_save/after_save is not triggered when attribute updates to nil? And how to trigger it?

Update:

Ok. I have another way to describe this. I'm saving an item, and Base.save is called on this item and all of its children. And since some of them are not this items children anymore, because I've unchecked them, save is not called on them. It sounds a little bit clearer. But still it's the same question described with another words. Why if a record is updated (some weird way though) and it's parent_id is changed, rails don't make it like an update?

======================================================================

My items have many-to-one association with themselves. I want to create comments to items when item changes his parent item. And everything works fine when item.superitem_id changes from nil to some id, or from some id to another id. But nothing happens, when item.superitem_id changes from some id to nil.


In the first case log shows:

UPDATE "items" SET "superitem_id" = 3, "updated_at" = '2011-04-12 23:07:05.566609' WHERE "items"."id" = 5

And in the second one:

UPDATE "items" SET "superitem_id" = NULL WHERE "items"."superitem_id" = 3 AND "items"."id"



So. Item is definitely changed. But why it's not updated and before_save is not called?


Model:

class Item < ActiveRecord::Base

  before_save :generate_comments

  has_many :subitems, :class_name => "Item", :foreign_key => "superitem_id"
  belongs_to :superitem, :class_name => "Item"

  private
    def generate_comments
      @comment = self.comments.build(:content => "Test: #{self.superitem_id}")
      @comment.save
    end

end

View with checkboxes from "HABTM checkboxes" railscast:

<% for subitem in @potential_subitems %>
  <%= check_box_tag "item[subitem_ids][]", subitem.id, @item.subitems.include?(subitem) %>
<% end %>

And Controller:

def update
  params[:item][:subitem_ids] ||= []
  @item = Item.find(params[:id])
  @item.update_attributes(params[:item])
end
like image 803
fetsh Avatar asked Feb 01 '26 22:02

fetsh


1 Answers

My wild guess is that on the 2nd case your association is saved (even though it's the same table) so rails doesn't see it as an update on "self". Check this post to force a callback on a belongs_to with "touch" :

"Before Save" callback on associations

like image 62
charlysisto Avatar answered Feb 04 '26 14:02

charlysisto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!