我为迁移文件中的列添加了默认值,但它不会以仅在数据库中显示为空字符串的形式提交。我可以使用下拉菜单选择其他类别,这些类别将保存,但是默认值“所有用户”将不会保存。
我在Rails 4.2.4上
迁移文件
class AddPrivacyLevelToArticles < ActiveRecord::Migration
def change
add_column :articles, :privacy_level, :string, default: "All Users"
end
end
我的表单中的字段。
<div class="form-group private_categories">
<%= f.label :privacy_level, { :class => "col-sm-2 control-label" } %>
<div class="col-sm-4">
<%= f.select :privacy_level, Article::PRIVACY_CATEGORIES,
{ include_blank: 'Please Select' }, class: "form-control" %>
</div>
</div>
在文章模型中
PRIVACY_CATEGORIES = ["Me only", "My Organization", "Multiple Organizations"]
答案 0 :(得分:1)
您可以使用枚举。 Doc
# models/article.rb
enum privacy_level: { all_users: 0, me_only: 1,
my_organization: 2,
multiple_organizations: 3}
#or
enum privacy_level: [:all_users, :me_only,
:my_organization,
:multiple_organizations]
#migration
add_column :articles, :privacy_level, :integer, default: 0
# View - form
Article.privacy_levels
=> {"all_users" => 0, "me_only" => 1 ...}