How to set default values in Rails?

后端 未结 17 1360
醉话见心
醉话见心 2020-11-28 04:39

I\'m trying to find the best way to set default values for objects in Rails.

The best I can think of is to set the default value in the new method in

相关标签:
17条回答
  • 2020-11-28 04:57

    For boolean fields in Rails 3.2.6 at least, this will work in your migration.

    def change
      add_column :users, :eula_accepted, :boolean, default: false
    end
    

    Putting a 1 or 0 for a default will not work here, since it is a boolean field. It must be a true or false value.

    0 讨论(0)
  • 2020-11-28 04:57

    Generate a migration and use change_column_default, is succinct and reversible:

    class SetDefaultAgeInPeople < ActiveRecord::Migration[5.2]
      def change
        change_column_default :people, :age, { from: nil, to: 0 }
      end
    end
    
    0 讨论(0)
  • 2020-11-28 04:58

    If you are referring to ActiveRecord objects, you have (more than) two ways of doing this:

    1. Use a :default parameter in the DB

    E.G.

    class AddSsl < ActiveRecord::Migration
      def self.up
        add_column :accounts, :ssl_enabled, :boolean, :default => true
      end
    
      def self.down
        remove_column :accounts, :ssl_enabled
      end
    end
    

    More info here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

    2. Use a callback

    E.G. before_validation_on_create

    More info here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002147

    0 讨论(0)
  • 2020-11-28 05:01

    A potentially even better/cleaner potential way than the answers proposed is to overwrite the accessor, like this:

    def status
      self['name_of_var'] || 'desired_default_value'
    end
    

    See "Overwriting default accessors" in the ActiveRecord::Base documentation and more from StackOverflow on using self.

    0 讨论(0)
  • 2020-11-28 05:03

    The suggestion to override new/initialize is probably incomplete. Rails will (frequently) call allocate for ActiveRecord objects, and calls to allocate won't result in calls to initialize.

    If you're talking about ActiveRecord objects, take a look at overriding after_initialize.

    These blog posts (not mine) are useful:

    Default values Default constructors not called

    [Edit: SFEley points out that Rails actually does look at the default in the database when it instantiates a new object in memory - I hadn't realized that.]

    0 讨论(0)
  • 2020-11-28 05:04

    You can also try change_column_default in your migrations (tested in Rails 3.2.8):

    class SetDefault < ActiveRecord::Migration
      def up
        # Set default value
        change_column_default :people, :last_name, "Smith"
      end
    
      def down
        # Remove default
        change_column_default :people, :last_name, nil
      end
    end
    

    change_column_default Rails API docs

    0 讨论(0)
提交回复
热议问题