1

In this SO article I can see how to add a default value to a certain table:

Add a default value to a column through a migration

change_column :shops, :currency_id, :integer, :default => 1

I have another table currencies that has an ID and also a ISO_Name. I want the system to use EUR as default value. But it's possible that this has ID 5 or ID 1 or ...

So my question: How can I define a default value that is based on the result of a query? For example Currency.find_by_iso_code('EUR').id

Community
  • 1
  • 1
rept
  • 2,086
  • 1
  • 26
  • 44
  • 1
    if you have the field as iso_name, then why you are using iso_code. It can be done that you have mentioned change_column :shops, :currency_id, :integer, :default => Currency.find_by_iso_name('EUR').id – Bachan Smruty Jun 27 '13 at 09:11
  • 1
    You are absolutely right, it's as easy as that! Currency.find_by_iso_name('EUR').id works. If you add this as I'll mark as answer. – rept Jun 27 '13 at 15:30
  • good to know that it worked. By the way I have added it as answer :) – Bachan Smruty Jun 27 '13 at 15:48

2 Answers2

1

As you have iso_name field in the currencies, you can achieve it by the following code.

change_column :shops, :currency_id, :integer, :default => Currency.find_by_iso_name('EUR').id 
Bachan Smruty
  • 5,686
  • 1
  • 18
  • 23
0

How about:

class SetDefaultCurrencyForShops < ActiveRecord::Migration
  def up
    currency = Currency.find_by_iso_code('EUR')
    if currency
      change_column :shops, :currency_id, :integer, :default => currency.id
    end
  end
end
Ju Liu
  • 3,939
  • 13
  • 18