嵌套表格行为 [英] nested form & habtm

查看:58
本文介绍了嵌套表格行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试保存到habtm关系中的联接表中,但是我遇到了问题.

I am trying to save to a join table in a habtm relationship, but I am having problems.

从我的角度来看,我传递的组ID为:

From my view, I pass in a group id with:

<%= link_to "Create New User", new_user_url(:group => 1) %>

 

# User model (user.rb)
class User < ActiveRecord::Base  
  has_and_belongs_to_many :user_groups
  accepts_nested_attributes_for :user_groups
end

 

# UserGroups model (user_groups.rb)
class UserGroup < ActiveRecord::Base
  has_and_belongs_to_many :users
end

 

# users_controller.rb
def new
  @user = User.new(:user_group_ids => params[:group])
end

在新用户视图中,我可以访问User.user_groups对象,但是在提交表单时,不仅不将其保存到我的联接表(user_groups_users)中,而且该对象也不再存在.其他所有对象除了用户组,我的User对象的属性都是持久的.

in the new user view, i have access to the User.user_groups object, however when i submit the form, not only does it not save into my join table (user_groups_users), but the object is no longer there. all the other objects & attributes of my User object are persistent except for the user group.

我刚刚开始学习Rails,所以也许我在概念上在这里缺少一些东西,但是我一直在为此苦苦挣扎.

i just started learning rails, so maybe i am missing something conceptually here, but i have been really struggling with this.

推荐答案

您是否考虑过仅将用户添加到控制器中的组中,而不是使用accepts_nested_attributes_for?这样,您就不需要来回传递user_group_id.

Instead of using accepts_nested_attributes_for, have you considered just adding the user to the group in your controller? That way you don't need to pass user_group_id back and forth.

在users_controller.rb中:

In users_controller.rb:

def create
  @user = User.new params[:user]
  @user.user_groups << UserGroup.find(group_id_you_wanted)
end

这样,您还可以阻止人们篡改表单并将自己添加到他们想要的任何组中.

This way you'll also stop people from doctoring the form and adding themselves to whichever group they wanted.

这篇关于嵌套表格行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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