0

I'm in the following situation, taking over an existing website, I have model User which has many devices like that:

has_many :devices, :through => :credits

When I create a device it creates a credit, but some of the attributes of the credits are null. I'd like to know if there's a way to control the creation of this credit and make sure nothing is null in the credit created for the database.

Thanks in advance

Denis Davydov
  • 463
  • 2
  • 8
  • 22

1 Answers1

0

Recommended: Use default values in your credits database table. You can use a database migration to do this.

class AddDefaultValuesToCredits < ActiveRecord::Migration
  def change
    change_column :credits, :value1, :boolean, default: false
    change_column :credits, :value2, :string, default: 'words'
    # change other columns
  end
end

If no explicit value is specified for value1 or value2, they'll default to false and 'words', respectively.

Alternative: You can also set default values in your Credit model.

class Credit < ActiveRecord::Base
  after_initialize :set_values, unless: persisted?

  # other model code

  def set_values
    if self.new_record?
       self.value1 = false if self.value.nil? # initial boolean value
       self.value2 ||= 'words' # initial string value
       # other values
    end
  end
Joe Kennedy
  • 9,365
  • 7
  • 41
  • 55
  • `after_initialize` is considered hacky, because that code is going to be run upon initialization of every single `Credit` object "magically". I would recommend going with the database migration only. – Ryan Bigg Mar 13 '14 at 22:27
  • Good to know Ryan. I figured I'd give a couple of options. I'll update my answer to reflect the recommendation of using a migration. – Joe Kennedy Mar 13 '14 at 22:33
  • @RyanBigg What do you mean by "magically"? I've seen people recommend after_initialize to set default values because they will apply even if you just call `Class.new` unlike database defaults – Rafael Ramos Bravin Mar 13 '14 at 23:01
  • @RyanBigg You may see some of this discussion in the answers of [this](http://stackoverflow.com/questions/328525/how-can-i-set-default-values-in-activerecord) question – Rafael Ramos Bravin Mar 13 '14 at 23:17
  • @RafaelRamosBravin highest voted answer is from 2011, and is therefore probably irrelevant for Rails today. – Ryan Bigg Mar 14 '14 at 03:00
  • @RyanBigg I was last edited oct 2012 though. Anyway, I was just curious about what you meant with "magically". – Rafael Ramos Bravin Mar 14 '14 at 19:27