Rails的 - 如何存储"&的has_many QUOT;在数据库复选框关联? [英] Rails - how to store "has_many" checkboxes association in database?
问题描述
我有表用户并表的类别
这两个表之间的关系:
- 用户
的has_many:类
- 类
belongs_to的:用户
- user
has_many :categories
- category
belongs_to :user
我想用户的(标准)编辑页面上显示的类别与复选框列表。当这个用户将检查一些复选框,我想救他们,然后显示作为托运时,他打开网页的下一次。
I would like to display on the user's (standard) edit page the list of categories with checkboxes. When this user would check some of the checkboxes, I would like to save them and then display as checked when he open the page the next time.
但如何呈现在视图中的复选框?以及如何存储什么复选框用户数据库检查信息?
我的第一个想法是希望建立像一个表的 user_categories 与 USER_ID
和 CATEGORY_ID
,但不知道这种方法是多么有效。
But how to render the checkboxes in the view? And how to store information about what checkboxes the user checked in database?
My first idea was like to create a table like user_categories with user_id
and category_id
, but not sure how effective this approach is.
什么是时下执行这一任务的最佳方法是什么?
What's the best way to implement this task nowadays?
推荐答案
不多,最近除了大力引进参数的改变。你仍然想使用一个 has_and_belongs_to_many
或的has_many:通过
的关系,然后就直接分配关系的ID。你需要设置传递一个ID阵列进行选择,使得他们在喜欢 {用户的一种形式:{category_ids => [1,2,3]}
。
Not much has changed recently except for the introduction of strong parameters. You still want to use either a has_and_belongs_to_many
or has_many :through
relationship and then just assign the ids of the relationship directly. You'll need to setup a form that passes an array of ids that are selected so that they come in like {user: {category_ids => [1,2,3]}
.
class User < ActiveRecord::Base
has_and_belongs_to_many :categories
end
在控制器
def update
current_user.update(user_params)
end
def user_params
params[:user].permit(
{:category_ids => []}
)
end
这篇关于Rails的 - 如何存储&QUOT;&的has_many QUOT;在数据库复选框关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!