nested form & habtm

流过昼夜 提交于 2019-12-10 09:25:06

问题


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

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

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.

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


回答1:


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.

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.




回答2:


What does your create method look like in users_controller.rb?

If you're using the fields_for construct in your view, for example:

<% user_form.fields_for :user_groups do |user_groups_form| %>

You should be able to just pass the params[:user] (or whatever it is) to User.new() and it will handle the nested attributes.




回答3:


Expanding on @jimworm 's answer:

groups_hash = params[:user].delete(:groups_attributes)
group_ids = groups_hash.values.select{|h|h["_destroy"]=="false"}.collect{|h|h["group_id"]}

That way, you've yanked the hash out of the params hash and collected the ids only. Now you can save the user separately, like:

@user.update_attributes(params[:user])

and add/remove his group ids separately in one line:

# The next line will add or remove items associated with those IDs as needed
# (part of the habtm parcel)
@user.group_ids = group_ids


来源:https://stackoverflow.com/questions/3026002/nested-form-habtm

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