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?
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?
class Like
def after_initialize
self.politics = false
end
end
i = Like.new
i.politics #=> false
class Like
attr_accessor_with_default :politics, false
end
i = Like.new
i.politics #=> false
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
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 super
is called on the first line of the function.
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.
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...