Joe Bloggos
Joe Bloggos

Reputation: 889

Rails default to a defined value

Hello I was wondering what the correct way to a defined default value as in

class SetDefault < ActiveRecord::Migration
  def change
    change_column :table_name, :column_name, :type, default: "Your value"
  end
end

but instead of "Your Value" it was @yourvalue which is stored in a @settings model

 class SetDefault < ActiveRecord::Migration
      def change
        change_column :table_name, :column_name, :type, default: @settings.yourvalue
      end
    end

class CreateSettings < ActiveRecord::Migration[5.2]
  def change
    create_table
            t.string :yourvalue
         t.timestamps
    end
  end
end

@yourvalue would be defined and updated by a user

Upvotes: 1

Views: 47

Answers (2)

t56k
t56k

Reputation: 6981

I would set it on the model so your migrations remain non-reliant on previous states of the data therein.

class TableName < ApplicationRecord
  before_create :add_defaults

  # whatever

  private

  def add_defaults
    self.column_name = Setting.find(1).default_value unless column_name
  end
end

This way you won't be invoking ActiveRecord from the migration, and your app will still work if you deploy it somewhere and run the migrations before adding a Setting record. You'll likely need a fully-migrated database before adding any data.

Upvotes: 1

Raj
Raj

Reputation: 22926

Migrations are normal Ruby classes. You can write Rails code within them. Eg. you can access your models.

class SetDefault < ActiveRecord::Migration
   def change
     change_column :table_name, :column_name, :string, default: Setting.find(1).yourvalue
   end
end

Replace Setting.find(1) with whatever logic you need to filter.

Upvotes: 1

Related Questions