I'm using rails and I want to make it so that attr_accessor :politics
is set, by default, to false.
Does anyone know how to do this and is able to explain it in simple terms for me?
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
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:
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...
来源:https://stackoverflow.com/questions/6715468/attr-accessor-default-values