How to initialize an ActiveRecord with values in Rails?

前端 未结 5 1715
情话喂你
情话喂你 2020-12-17 08:35

In plain java I\'d use:

public User(String name, String email) {
  this.name = name;
  this.email = f(email);
  this.admin = false;
}

5条回答
  •  情深已故
    2020-12-17 09:03

    I was searching for something similar this morning. While setting a default value in the database will obviously work, it seems to break with Rails' convention of having data integrity (and therefore default values?) handled by the application.

    I stumbled across this post. As you might not want to save the record to the database immediately, I think the best way is to overwrite the initialize method with a call to write_attribute().

    def initialize
      super
      write_attribute(name, "John Doe")
      write_attribute(email,  f(email))
      write_attribute(admin, false)
    end
    

提交回复
热议问题