问题
Heres the situation: I have a Category model, which needs to have an attribute where the user can select multiple items from 3-4 predefined values (meaning only I can add more, the admins can't, so there is no separate model for those 3-4 options).
Enum would be great but with that, only 1 option can be selected. Since I am using Postgres, I am thinking about using an array type attribute to store the selected values.
Is there a simpler, more efficient way to do this or another field type which I am just not aware of?
UPDATE (What I chose to do):
Migration (Postgres 9.3): add_column :categories, :settings, :string, array: true, default: '{}'
Controller:
Added :settings => []
to permitted params.
View: <%= f.select :settings, %w[a b c], {}, :multiple => true %>
So if I would like to get all categories where setting 'a' is present then I an do:
Category.where("'a' = ANY (settings)")
回答1:
I am thinking about using an array type attribute to store the selected values.
You can serialize your field to save values as array or hash in database. For this first you'll have to add a field in categories table by creating a migration
class some_migration
def change
add_column :categories, :some_field, :text
end
end
In model tell rails to use it as a serializable field
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/rails-4-field-type-for-multiselect-with-predefined-values