如何初始化一个ActiveRecord在Rails的价值观? [英] How to initialize an ActiveRecord with values in Rails?

查看:127
本文介绍了如何初始化一个ActiveRecord在Rails的价值观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在普通的Java我会使用:

In plain java I'd use:

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


不过,我无法找到一个简单的标准的方式做在轨(3.2.3),用ActiveRecords。


However, I couldn't find a simple standard way to do in rails (3.2.3), with ActiveRecords.

def initialize(attributes = {}, options = {})
  @name  = attributes[:name]
  @email = f(attributes[:email])
  @admin = false
end

但它可能会从DB 记录时错过>

通过重写它:

def after_initialize(attributes = {}, options = {})
  ...
end

或宏:

after_initialize : my_own_little_init
def my_own_little_init(attributes = {}, options = {})
  ...
end

,但有可能是<一href="http://stackoverflow.com/questions/328525/what-is-the-best-way-to-set-default-values-in-activerecord">some德precation问题。

有一些其他链接<一个href="http://stackoverflow.com/questions/1550688/how-do-i-create-a-default-value-for-attributes-in-rails-activerecords-model">in SO 的,但它们可以是过期失

There are some other links in SO, but they may be out-of-date.

因此​​,什么是使用正确的/标准方法?

推荐答案

您的默认值应该在架构中定义时,将适用于所有记录。因此,

Your default values should be defined in your Schema when they will apply to ALL records. So

def change
  creates_table :posts do |t|
    t.boolean :published, default: false
    t.string :title
    t.text :content
    t.references :author
    t.timestamps
  end
end

在这里,每一个新的邮政将有假的出版。如果你想在对象级别的默认值,最好使用工厂风格的实现:

Here, every new Post will have false for published. If you want default values at the object level, it's best to use Factory style implementations:

User.build_admin(params)

def self.build_admin(params)
  user = User.new(params)
  user.admin = true
  user
end

这篇关于如何初始化一个ActiveRecord在Rails的价值观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆