简体   繁体   中英

Rails 4: Changing data in model before saving

I just read the following two answers to the question: How do I change the parameters for an object that is about to be saved (in the model)?

1)

class User < ActiveRecord::Base
  def username=(val)
    write_attribute(:username, val.downcase)
  end
end

2)

before_save do
  self.username = self.username.downcase
end

Can anyone evaluate if one solution is "better" as the other for various reasons? Or can they be considered "the same"?

Thank you guys!

One difference is that in option (1), the username attribute will be lowercase as soon as you assign it, whereas with option (2), it will not be converted until the record is saved. Therefore, option (1) may be preferable if the value of username affects other steps that occur before saving.

Also, I find option (1) to be better in terms of readability/maintainability because it is clear that the code relates directly to assignment of the username. In option (2) this is a bit more implicit.

Side note: you should probably check for nil because the above code will result in an error if username is assigned a nil value (due to calling downcase on nil):

class User < ActiveRecord::Base
  def username=(val)
    val = val.downcase unless val.nil?
    write_attribute(:username, val)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM