在Ruby on Rails中添加布尔列值

时间:2014-11-26 01:59:16

标签: ruby-on-rails ruby boolean activeadmin

我正在开发一个创建网络博客的Ruby on Rails项目。我希望在Post模型中添加一个名为features的布尔数据库字段。该字段应该可以通过我添加的活动管理界面进行编辑。

我使用了以下代码,但我甚至没有在网站上显示另一个专栏。

$rails generate migration addFeatured featured:boolean
$rake db:migrate

我是Ruby on Rails的新手,非常感谢任何帮助。

index.html.erb文件(views)中的相关代码:

<th>Featured Post</th>
<td><%= post.featured %></td>

Schema.rb:

ActiveRecord::Schema.define(:version => 20141126015126) do

create_table "active_admin_comments", :force => true do |t|
 t.string   "namespace"
 t.text     "body"
 t.string   "resource_id",   :null => false
 t.string   "resource_type", :null => false
 t.integer  "author_id"
 t.string   "author_type"
 t.datetime "created_at",    :null => false
 t.datetime "updated_at",    :null => false
end

add_index "active_admin_comments", ["author_type", "author_id"], :name =>    "index_active_admin_comments_on_author_type_and_author_id"
add_index "active_admin_comments", ["namespace"], :name => "index_active_admin_comments_on_namespace"
add_index "active_admin_comments", ["resource_type", "resource_id"], :name => "index_active_admin_comments_on_resource_type_and_resource_id"

create_table "admin_users", :force => true do |t|
 t.string   "email",                  :default => "", :null => false
 t.string   "encrypted_password",     :default => "", :null => false
 t.string   "reset_password_token"
 t.datetime "reset_password_sent_at"
 t.datetime "remember_created_at"
 t.integer  "sign_in_count",          :default => 0
 t.datetime "current_sign_in_at"
 t.datetime "last_sign_in_at"
 t.string   "current_sign_in_ip"
 t.string   "last_sign_in_ip"
 t.datetime "created_at",                             :null => false
 t.datetime "updated_at",                             :null => false
end

add_index "admin_users", ["email"], :name => "index_admin_users_on_email", :unique => true
add_index "admin_users", ["reset_password_token"], :name => "index_admin_users_on_reset_password_token", :unique => true

create_table "comments", :force => true do |t|
 t.string   "commenter"
 t.text     "body"
 t.integer  "post_id"
 t.datetime "created_at", :null => false
 t.datetime "updated_at", :null => false
end

add_index "comments", ["post_id"], :name => "index_comments_on_post_id"

create_table "posts", :force => true do |t|
 t.string   "name"
 t.string   "title"
 t.text     "content"
 t.datetime "created_at", :null => false
 t.datetime "updated_at", :null => false
end

end

2 个答案:

答案 0 :(得分:7)

你需要这样做:

$ rails g migration AddFeaturedToPosts featured:boolean

如果您已经使用以下名称创建了此迁移文件:201411......_ add_featured.rb,则首先回滚:

$ rake db:rollback STEP=1 // or use VERSION=201411....

修改它:

add_column :posts, :featured, :boolean

然后:

$ rake db:migrate

答案 1 :(得分:2)

您应该使用rails generate migration AddFeaturedToMyModelName featured:boolean来迁移以添加到名为MyModelName的模型中。如果rake db:migrate确实包含类似..._add_featured.rb的迁移,那么在生成正确的迁移之前执行rake db:rollback STEP=1,然后调用rake db:migrate