开发者

Save in ActiveRecord

开发者 https://www.devze.com 2022-12-08 14:42 出处:网络
When working with a m开发者_Python百科odel, when do you need to explicitly save?Say in a setter

When working with a m开发者_Python百科odel, when do you need to explicitly save? Say in a setter

def name=(n) 
  self.name = n
end

Do I need a self.save?


For your specific example, you'd need to do something like this:

class MyClass < ActiveRecord::Base
  def name=(n) 
    self.name = n
    save!
  end
end

I'd recommend using save! instead of save unless you plan to check for errors since save! will throw an exception but save will fail silently.

BTW, I'm guessing your example was just a quick unrealistic one, since you're overriding the existing ActiveRecord setter function for the "name" field. ActiveRecord accessor methods are quite different than plain Ruby accessors so if you create "name=" on top of the auto-generated "name=" method, you're screwed.


Save persists your changes to the database, if you want to persist your changes you have to call save.

In the example you gave you wouldn't call save in the setter, you'd do something like:

my_model.name = 'foo'
my_model.save


You don't need to do anything. You can do a save later if that's what works best for me.

If you're doing many setters for a record, there's no point in doing a save each time.

model.foo1 = '1'
model.save

model.foo2 = '2'
model.save

model.foo3 = '3'
model.save

Depending on how you're going to use it, you can just do the final save. As long as you do a save eventually...

0

精彩评论

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

关注公众号