在Rails迁移中设置不同的默认值? [英] Setting different default values in rails migrations?
问题描述
我正在尝试编写一个迁移,它看起来像这样:
I'm trying to write a migration and it looks something like this:
class AddStatusToWorks < ActiveRecord::Migration
def self.up
change_table :works do |t|
t.string :status
end
end
def self.down
change_table :works do |t|
t.remove :status
end
end
end
问题是,我想基于表"complete"中的布尔值为"status"设置不同的默认值.如果complete = true,则状态="complete".如果不是,则状态=正在进行中". (我想要一个字符串而不是将其保留为布尔值的原因是因为我希望在那里可以有两个以上的身份证明.)任何想法该怎么做?我是否可以在其中粘贴if语句
Thing is, I want to set different default values for "status" based on a boolean value that's already in the table, "complete." If complete = true, status = "complete." If not, status = "work in progress." (The reason I want a string instead of keeping complete as the boolean is because I want there to be able to be more than two possibilites for status.) Any idea how to do that? Do I just stick an if statement in there like this
change_table :works do |t|
t.string :status
if (:complete == true)
:value => "complete"
else
:value => "wip"
end
嗯,所以看起来不太正确.我在谷歌上搜索了一下,发现可以设置:default值,但这并不是我想要的.任何想法/帮助将是可爱的.谢谢!
Er, so that doesn't look quite right. I googled a bit and found that you can set :default values, but that's not quite what I'm going for. Any ideas/help would be lovely. Thanks!
推荐答案
您根本不需要默认值,只需要添加新列并为其赋值即可.这样的事情应该起作用:
You don't need a default at all, you just need to add the new column and give it values. Something like this should work:
def self.up
change_table :works do |t|
t.string :status
end
Works.reset_column_information
Works.where(:complete => true).update_all(:status => 'complete')
Works.where(:complete => [false, nil]).update_all(:status => 'wip')
end
请参阅迁移指南,以获取有关reset_column_information
.
您也可以直接在数据库中执行此操作,但必须注意不同的布尔表示形式(PostgreSQL需要't'
和'f'
,MySQL需要1
和0
,SQLite需要1
和0
,但Rails错误地使用't'
和'f'
,...):
You could also do it straight in the database but you have to be careful about different boolean representations (PostgreSQL wants 't'
and 'f'
, MySQL wants 1
and 0
, SQLite wants 1
and 0
but Rails mistakenly uses 't'
and 'f'
, ...):
t = connection.quote(true)
connection.execute(%Q{
update works
set status = case complete
when #{t} then 'complete'
else 'wip'
end
})
这篇关于在Rails迁移中设置不同的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!