开发者

before_update syntax

开发者 https://www.devze.com 2023-02-19 19:58 出处:网络
post.rb Model after_update :assign_owner def assign_owner开发者_运维问答 self.owner = \"test\" end

post.rb Model

   after_update :assign_owner

   def assign_owner开发者_运维问答
      self.owner = "test"
   end

The above method works in terminal but does not change the value of Post.new.owner in Rails. What am I missing?


This is an after update (object needs to be saved) so

post = Post.new.save

Then

post.owner  # will be test

If you wanna do this you may want to use after_initialize

for e.g in post.rb

class Post < ActiveRecord::Base
  protected
    def after_initialize
      self.owner = "test
    end
end


after_update only fires when you update your object. after_update will not call when you create.

You can use after_create callback when you want to call method on creating new object.

  after_create :assign_owner
   after_update :assign_owner

   def assign_owner
      self.owner = "test"
   end


after_update and after_create are called after the object is saved. You do set the value of the owner but you don't save it.

Two possible options: use before_update instead --> your object is not yet saved and your change will be saved correctly.

Or use after_update and write it as follows:

def assign_owner
  self.update_attribute :owner, "test"
end

Note: any callback will only be called right before or right after saving, so Post.new.owner will still be wrong. But Post.create(:context => 'blabla') should trigger it correctly (or Post.new.save).

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号