Check whether you migrate up or down in Rails 3.1?

13 views
Skip to first unread message

Linus Pettersson

unread,
Jan 2, 2012, 4:49:35 PM1/2/12
to rubyonra...@googlegroups.com
Hi!

In Rails 3.1 there is only one method for migrations called 'change'.

I want to run some code in a migration only when migrating up, not down. Is that possible?

The issue I have is that this code is inside a migration file from Active Admin:

# Create a default user
AdminUser.create!(:email => 'ad...@example.com', :password => 'password', :password_confirmation => 'password')

So, when I try to migrate down this will fail because there is already a user present.

Any ideas?

Regards
Linus

Peter Vandenabeele

unread,
Jan 2, 2012, 5:52:56 PM1/2/12
to rubyonra...@googlegroups.com
On Mon, Jan 2, 2012 at 10:49 PM, Linus Pettersson <linus.pe...@gmail.com> wrote:
Hi!

In Rails 3.1 there is only one method for migrations called 'change'.

Not exaclty. up and down still exist (but now instance methods instead of
class methods).

Google ("rails guide migrations").
 

I want to run some code in a migration only when migrating up, not down. Is that possible?

Yes.
 

The issue I have is that this code is inside a migration file from Active Admin:

# Create a default user
AdminUser.create!(:email => 'ad...@example.com', :password => 'password', :password_confirmation => 'password')

So, when I try to migrate down this will fail because there is already a user present.


And what about:

def up
  AdminUser.create!(:email => 'ad...@example.com', :password => 'password', :password_confirmation => 'password')
end

def down
  u = AdminUser.find_by_email('ad...@example.com')
  u.destroy
end

  

Any ideas?


If the down migration is really impossible to do (which can happen;
e.g because you miss data to reset everything to the original state)
than you can raise ActiveRecord::IrreversibleMigration exception
in the down migration.

HTH,

Peter

-- 
Peter Vandenabeele
http://twitter.com/peter_v

Linus Pettersson

unread,
Jan 2, 2012, 6:15:50 PM1/2/12
to rubyonra...@googlegroups.com, pe...@vandenabeele.com
I see.

Thank you very much Peter!

Regards
Linus
Reply all
Reply to author
Forward
0 new messages