如何在 Rails 中设置默认值? [英] How to set default values in Rails?

查看:49
本文介绍了如何在 Rails 中设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试寻找在 Rails 中为对象设置默认值的最佳方法.

I'm trying to find the best way to set default values for objects in Rails.

我能想到的最好的方法是在控制器的new方法中设置默认值.

The best I can think of is to set the default value in the new method in the controller.

如果这是可以接受的或者是否有更好的方法来做到这一点,是否有人有任何意见?

Does anyone have any input if this is acceptable or if there's a better way to do it?

推荐答案

正确"在 Ruby 中是一个危险的词.通常有不止一种方法可以做任何事情.如果您知道您总是希望该表中该列的默认值,那么在数据库迁移文件中设置它们是最简单的方法:

"Correct" is a dangerous word in Ruby. There's usually more than one way to do anything. If you know you'll always want that default value for that column on that table, setting them in a DB migration file is the easiest way:

class SetDefault < ActiveRecord::Migration
  def self.up
    change_column :people, :last_name, :type, :default => "Doe"
  end

  def self.down
    # You can't currently remove default values in Rails
    raise ActiveRecord::IrreversibleMigration, "Can't remove the default"
  end
end

因为 ActiveRecord 会自动发现您的表和列属性,这将导致在任何标准 Rails 应用程序中使用它的任何模型中设置相同的默认值.

Because ActiveRecord autodiscovers your table and column properties, this will cause the same default to be set in any model using it in any standard Rails app.

但是,如果您只想在特定情况下设置默认值——比如说,它是一个与其他人共享一个表的继承模型——那么另一种优雅的方法是在创建模型对象时直接在 Rails 代码中进行设置:

However, if you only want default values set in specific cases -- say, it's an inherited model that shares a table with some others -- then another elegant way is do it directly in your Rails code when the model object is created:

class GenericPerson < Person
  def initialize(attributes=nil)
    attr_with_defaults = {:last_name => "Doe"}.merge(attributes)
    super(attr_with_defaults)
  end
end

然后,当您执行 GenericPerson.new() 时,除非您覆盖它,否则它始终会将Doe"属性滴入 Person.new()用别的东西.

Then, when you do a GenericPerson.new(), it'll always trickle the "Doe" attribute up to Person.new() unless you override it with something else.

这篇关于如何在 Rails 中设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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