How to set default values in Rails?

后端 未结 17 1361
醉话见心
醉话见心 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 05:04

    In case you're dealing with a Model, you can use the Attriutes API in Rails 5+ http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute

    just add a migration with a proper column name and then in the model set it with:

    class StoreListing < ActiveRecord::Base
      attribute :country, :string, default: 'PT'
    end
    
    0 讨论(0)
  • 2020-11-28 05:05

    First of all you can't overload initialize(*args) as it's not called in all cases.

    Your best option is to put your defaults into your migration:

    add_column :accounts, :max_users, :integer, :default => 10
    

    Second best is to place defaults into your model but this will only work with attributes that are initially nil. You may have trouble as I did with boolean columns:

    def after_initialize
      if new_record?
        max_users ||= 10
      end
    end
    

    You need the new_record? so the defaults don't override values loaded from the datbase.

    You need ||= to stop Rails from overriding parameters passed into the initialize method.

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

    You can override the constructor for the ActiveRecord model.

    Like this:

    def initialize(*args)
      super(*args)
      self.attribute_that_needs_default_value ||= default_value
      self.attribute_that_needs_another_default_value ||= another_default_value
      #ad nauseum
    end
    
    0 讨论(0)
  • 2020-11-28 05:09

    You could use the rails_default_value gem. eg:

    class Foo < ActiveRecord::Base
      # ...
      default :bar => 'some default value'
      # ...
    end
    

    https://github.com/keithrowell/rails_default_value

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

    If you're talking about ActiveRecord objects, I use the 'attribute-defaults' gem.

    Documentation & download: https://github.com/bsm/attribute-defaults

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