Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default values in models? -- in Ruby on Rails 3.1

In RoR 3.1, "validates" still doesn't have a way of setting default values in the models. Or is there? If not, what's the best way to set default values?

like image 416
Hopstream Avatar asked Oct 31 '11 05:10

Hopstream


3 Answers

One approach would be to set the default in your migration. This will be a property that will get set to your database. You can read more here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

The other approach is to set a before filter, something like before_save or before_create, and then check if the value on an attribute is nil, you can set it to something.

class Abc
   before_save :set_default

   protected

   def set_default
     self.xyz = "default" unless self.xyz
   end
end
like image 52
Wahaj Ali Avatar answered Nov 16 '22 11:11

Wahaj Ali


migration are best for setting default value
write a migration to update column and set default value

        self.up do 
           update_column :table_name,:column_name,:default=>your default value
         end
like image 45
Naveed Avatar answered Nov 16 '22 12:11

Naveed


This works well for me

class WorkLogEntry < ActiveRecord::Base 

  after_initialize do
    self.work_done_on ||= Time.zone.today
  end

  ...
end
like image 24
Darwin Avatar answered Nov 16 '22 12:11

Darwin