Rails 4字段类型,用于具有预定义值的多选 [英] Rails 4 field type for multiselect with predefined values

查看:74
本文介绍了Rails 4字段类型,用于具有预定义值的多选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里情况: 我有一个类别模型,该模型需要具有一个属性,用户可以在其中从3-4个预定义值中选择多个项目(这意味着只有我可以添加更多内容,而管理员不能添加,因此对于这3-4个对象没有单独的模型选项).

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).

枚举会很棒,但是只能选择1个选项. 由于我使用的是Postgres,因此我正在考虑使用数组类型属性来存储选定的值.

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):

迁移(Postgres 9.3): add_column:categories,:settings,:string,array:true,默认值:'{}'

Migration (Postgres 9.3): add_column :categories, :settings, :string, array: true, default: '{}'

控制器: 在允许的参数中添加了:settings => [].

Controller: Added :settings => [] to permitted params.

查看: <%= f.select :settings, %w[a b c], {}, :multiple => true %>

因此,如果我想获取所有设置为'a'的类别,那么我将这样做:

So if I would like to get all categories where setting 'a' is present then I an do:

Category.where("'a' = ANY (settings)")

推荐答案

我正在考虑使用数组类型属性来存储选定的值.

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

在模型中告诉Rails将其用作可序列化字段

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]

这篇关于Rails 4字段类型,用于具有预定义值的多选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆