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

In RoR 3.1, “validation” still has no way to set default values ​​in models. Or is there? If not, what is the way to set the default values?

+4
source share
4 answers

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

Another approach is to set the before filter, something like before_save or before_create, and then check if there is a value in the nil attribute, you can set it to something.

class Abc before_save :set_default protected def set_default self.xyz = "default" unless self.xyz end end 
+7
source

migration is best for setting a default
write the upgrade transition column and set the default value

  self.up do update_column :table_name,:column_name,:default=>your default value end 
+7
source

This works well for me

 class WorkLogEntry < ActiveRecord::Base after_initialize do self.work_done_on ||= Date.today end ... end 
+5
source

When the model receives form parameters with empty parameters, the fields of these fields will have the nil parameter. Therefore, if you initialize the same @foo = 'bar' and the user submission form with empty parameters [: foo], then Model.create (params [: model]) will have foo => nil.

  • You can check all the parameters before the object is created.
  • You can set default parameters in your database structure through migrations:

    create_table: comments do | t |
    t.text: comment ,: default => 'bar'
    end

0
source

All Articles