Ruby-on-rails attr_accessor 默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6715468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:37:06  来源:igfitidea点击:

attr_accessor default values

ruby-on-railsrubyattr-accessor

提问by Vasseurth

I'm using rails and I want to make it so that attr_accessor :politicsis set, by default, to false.

我正在使用 rails 并且我想将其attr_accessor :politics设置为默认情况下为 false。

Does anyone know how to do this and is able to explain it in simple terms for me?

有谁知道如何做到这一点,并能用简单的术语为我解释?

回答by Orlando

Rails has attr_accessor_with_defaultso you could write

Rails 有attr_accessor_with_default所以你可以写

class Like
  attr_accessor_with_default :politics,false
end

i = Like.new
i.politics #=> false

and thats all

就这样

UPDATE

更新

attr_accessor_with_defaulthas been deprecated in Rails 3.2.. you could do this instead with pure Ruby

attr_accessor_with_default已在 Rails 3.2 中被弃用。你可以用纯 Ruby 来代替

class Like
  attr_writer :politics

  def politics
    @politics || false
  end
end

i = Like.new
i.politics #=> false

回答by Vasseurth

If you define your attr_accessor, by default the value is nil. You can write to it, thereby making it !nil

如果您定义了attr_accessor,默认值为nil。你可以写信给它,从而使它!nil

回答by Naresh Dwivedi

class Song < ActiveRecord::Base
    def initialize(*args)
    super(*args)
      return unless self.new_record?
      self.play_count ||= 0
    end
end

In my opinion, I think this answer is good. Although we are overriding the initialize()method but since super is called on the first line of this method, it doesn't change anything to the base class initialize()method, rather this is a key feature of Object Oriented programming that we can override it, and add some more functionality at the time of initialization of objects. And also the initializer will not be skipped while reading objects from the database, since superis called on the first line of the function.

在我看来,我认为这个答案很好。虽然我们重写了该initialize()方法,但是由于在该方法的第一行调用了 super,它不会改变基类initialize()方法的任何内容,而是面向对象编程的一个关键特性,我们可以重写它,并添加一些对象初始化时的更多功能。而且从数据库读取对象时也不会跳过初始化程序,因为它super是在函数的第一行调用的。

回答by Thilo

You could use the virtus gem:

您可以使用 virtus gem:

https://github.com/solnic/virtus

https://github.com/solnic/virtus

From the README:

从自述文件:

Virtus allows you to define attributes on classes, modules or class instances with optional information about types, reader/writer method visibility and coercion behavior. It supports a lot of coercions and advanced mapping of embedded objects and collections.

Virtus 允许您使用有关类型、读写器方法可见性和强制行为的可选信息来定义类、模块或类实例的属性。它支持嵌入对象和集合的许多强制和高级映射。

It specifically supports default values.

它特别支持默认值

回答by mcmoyer

I've been using this form in ActiveRecord:

我一直在 ActiveRecord 中使用这个表单:

class Song < ActiveRecord::Base

    def initialize(*args)
      super(*args)
      return unless self.new_record?
      self.play_count ||= 0
    end
end

回答by Benjamin Tan Wei Hao

This is not done in attr_accessor, rather, in your migration.

这不是在 attr_accessor 中完成的,而是在您的迁移中完成的。

So .. you could perform a migration

所以..你可以执行迁移

(1) rails g migration ChangePoliticsColumnToDefaultValueFalse

(1) rails g migration ChangePoliticsColumnToDefaultValueFalse

(2) add this in def self.up

(2) 加入这个 def self.up

def self.up change_column :your_table, :politics, :boolean, :default => 0 end

def self.up change_column :your_table, :politics, :boolean, :default => 0 end

The bottom line is that default attributes are set in migrations.

最重要的是,默认属性是在迁移中设置的。

Hope this helps!

希望这可以帮助!

Edit:

编辑:

There are some similar questions too that have been answered well:

还有一些类似的问题也得到了很好的回答:

Like hereand here

喜欢这里这里

回答by Ganesh Shrivas

attr_accessor in rails are only virtual variable which is not store in database and it can be use only until active record not save or update in application. You can define attr_accessor in model like

rails 中的 attr_accessor 只是不存储在数据库中的虚拟变量,它只能在活动记录未在应用程序中保存或更新时使用。您可以在模型中定义 attr_accessor ,例如

class Contact < ActiveRecord::Base
attr_accessor :virtual_variable
end

and use in form like :-

并以如下形式使用:-

 <div class="field">
    <%= f.label :virtual %><br>
    <%= f.text_field :virtual %>
  </div>

and you can found these vartual variable value in controller param...

您可以在控制器参数中找到这些 vartual 变量值...