attr_accessor default values

落爺英雄遲暮 提交于 2019-11-28 06:41:45

Rails has attr_accessor_with_default so you could write

class Like
  attr_accessor_with_default :politics,false
end

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

and thats all

UPDATE

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

class Like
  attr_writer :politics

  def politics
    @politics || false
  end
end

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

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

You could use the virtus gem:

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.

It specifically supports default values.

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 first line of this method, it didn't change anything to the base class initialize method, rather this is key feature of Object Oriented programming that we can override it, and add some more functionality at the time of initialization of obects. And Also the initializer will not be skipped while reading objects from database, since super is called at the first line of the function.

I've been using this form in ActiveRecord:

class Song < ActiveRecord::Base

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

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

So .. you could perform a migration

(1) rails g migration ChangePoliticsColumnToDefaultValueFalse

(2) add this in def self.up

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 here and here

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

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!