如何使用 Rails 中的值初始化 ActiveRecord? [英] How to initialize an ActiveRecord with values in Rails?

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

问题描述

在纯 Java 中我会使用:

In plain java I'd use:

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

<小时>

但是,我无法在 Rails (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

但在创建 记录时可能会错过数据库

通过覆盖它:

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

或使用宏:

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

但可能存在一些弃用问题.

还有一些其他链接在 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

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

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