Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how (replace|create) an enum field on rails 2.0 migrations?

I would like to create an enum field at sone migration I'm doing, I tried searching in google but I can't find the way to do it in the migration

the only thing I found was

  t.column :status, :enum, :limit => [:accepted, :cancelled, :pending] 

but looks like the above code runs only on rails 1.xxx and since I'm running rails 2.0

this what I tried but it fails

class CreatePayments < ActiveRecord::Migration   def self.up     create_table :payments do |t|       t.string :concept       t.integer :user_id       t.text :notes       t.enum :status, :limit => [:accepted, :cancelled, :pending]        t.timestamps     end   end    def self.down     drop_table :payments   end end 

So, in case that isn't allowed, what do you think could be a good solution? just a text field, and validating from the model?

like image 513
Gabriel Sosa Avatar asked Mar 29 '09 01:03

Gabriel Sosa


2 Answers

You can manually specify the type by using the t.column method instead. Rails will interpret this as a string column, and you can simply add a validator to the model like Pavel suggested:

class CreatePayments < ActiveRecord::Migration   def self.up     create_table :payments do |t|       t.string :concept       t.integer :user_id       t.text :notes       t.column :status, "ENUM('accepted', 'cancelled', 'pending')"        t.timestamps     end       end    def self.down     drop_table :payments   end end  class Payment < ActiveRecord::Base   validates_inclusion_of :status, :in => %w(accepted cancelled pending) end 
like image 52
Adam Lassek Avatar answered Sep 21 '22 10:09

Adam Lassek


Look at tip #3 on http://zargony.com/2008/04/28/five-tips-for-developing-rails-applications

This exactly what you need!

 class User < ActiveRecord::Base    validates_inclusion_of :status, :in => [:active, :inactive]     def status      read_attribute(:status).to_sym    end     def status= (value)      write_attribute(:status, value.to_s)    end  end 

HTH

like image 20
Pavel Nikolov Avatar answered Sep 20 '22 10:09

Pavel Nikolov