简体   繁体   English

Rails 4:在保存之前更改模型中的数据

[英]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) 1)

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

2) 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. 区别在于,在选项(1)中,用户名属性一经分配便立即变为小写,而在选项(2)中,直到保存记录后才转换。 Therefore, option (1) may be preferable if the value of username affects other steps that occur before saving. 因此,如果用户名的值影响保存之前发生的其他步骤,则选项(1)可能更可取。

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. 另外,我发现选项(1)在可读性/可维护性方面更好,因为很明显代码直接与用户名的分配有关。 In option (2) this is a bit more implicit. 在选项(2)中,这有点隐含。

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): 旁注:您可能应该检查nil,因为如果为用户名分配了nil值,则上面的代码将导致错误(由于在nil上调用了downcase ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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