Rails的 - 如何存储"&的has_many QUOT;在数据库复选框关联? [英] Rails - how to store "has_many" checkboxes association in database?

查看:210
本文介绍了Rails的 - 如何存储"&的has_many QUOT;在数据库复选框关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表用户并表的类别

这两个表之间的关系:


  • 用户的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屋!

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