这里是这样的情况:我有一个分类模型,它需要有一个属性,用户可以从3-4预定义值中选择多个项(意味着只有我可以添加更多,管理员不能添加更多,所以这3-4选项没有单独的模型)。
Enum将是很棒的,但有了它,只能选择一个选项。因为我使用Postgres,所以我考虑使用数组类型属性来存储所选的值。
有没有一种更简单、更有效的方法来完成这个或另一个领域类型,而我只是不知道呢?
更新(我选择做的事情):
迁移(Postgres9.3): add_column :类别、:设置、:string、数组: true、默认值:{}
控制器:将:settings => []
添加到允许的params中。
视图: <%= f.select :settings, %w[a b c], {}, :multiple => true %>
因此,如果我想得到设置'a‘的所有类别,那么我就做:
Category.where("'a' = ANY (settings)")
发布于 2014-10-25 17:26:18
我正在考虑使用数组类型属性来存储所选的值。
可以通过serialize your field
将值保存为数据库中的数组或散列。首先,您必须通过创建迁移来在类别表中添加一个字段
class some_migration
def change
add_column :categories, :some_field, :text
end
end
在模型中,告诉rails将其用作可序列化的字段。
class Category < ActiveRecord::Base
serialize :some_field, Array
end
#this will allow you to do something like this:
category = Category.create(some_field: [some_value_1,some_value_2])
Category.find(category.id).preferences # => [some_value_1, some_value_2]
https://stackoverflow.com/questions/26564946
复制相似问题