nested form & habtm

橙三吉。 提交于 2019-12-05 15:36:00

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.

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.

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