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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With