Gab*_*osa 29 ruby migration ruby-on-rails
我想在我正在进行的sone迁移中创建一个枚举字段,我尝试在谷歌搜索,但我无法在迁移中找到方法
我发现的唯一的事情是
t.column :status, :enum, :limit => [:accepted, :cancelled, :pending]
Run Code Online (Sandbox Code Playgroud)
但看起来上面的代码只在rails 1.xxx上运行,因为我正在运行rails 2.0
这就是我尝试但它失败了
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
Run Code Online (Sandbox Code Playgroud)
那么,如果不允许,您认为什么是一个好的解决方案?只是一个文本字段,并从模型验证?
Ada*_*sek 37
您可以使用该t.column方法手动指定类型.Rails会将此解释为字符串列,您可以像Pavel建议的那样简单地向模型添加验证器:
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
Run Code Online (Sandbox Code Playgroud)
Pav*_*lov 24
请参阅http://zargony.com/2008/04/28/five-tips-for-developing-rails-applications上的#3提示
这正是你需要的!
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
Run Code Online (Sandbox Code Playgroud)
HTH
您可以尝试(非常)全面的jeff的enumerated_attribute gem或者使用这个简单的解决方法:
class Person < ActiveRecord::Base
SEX = [:male, :female]
def sex
SEX[read_attribute(:sex)]
end
def sex=(value)
write_attribute(:sex, SEX.index(value))
end
end
Run Code Online (Sandbox Code Playgroud)
然后将该sex属性声明为整数:
t.integer :sex
Run Code Online (Sandbox Code Playgroud)
这对我来说非常好!= d
添加以下内容:
活动记录模块
模块连接适配器 #:nodoc:
类表定义
def 枚举(*args)
选项= args.extract_options!
列名=参数
column_names.each { |名称| 列(名称,'枚举',选项)}
结尾
结尾
结尾
结尾
到 lib/enum/table_definition.rb 并将其包含在 init.rb 中。