Rails 4 field type for multiselect with predefined values

时间秒杀一切 提交于 2019-12-11 02:54:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!