Nested Form & habtm

I am trying to keep a connection table in a habtm relationship, but I'm having problems.

In my opinion, I pass the group id:

<%= 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, it not only does not save it in my connection table (user_groups_users), but the object no longer exists. all other objects and attributes of my User object remain constant, with the exception of a user group.

I was just starting to study rails, so maybe I missed something conceptually here, but I really struggled with it.

+4
source share
3 answers

Instead of using accepts_nested_attributes_for, have you considered simply adding a user to a group in your controller? This way you do not 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 

Thus, you also forbid people to process the form and add themselves to the group that they wanted.

+4
source

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

If you use the fields_for construct in your view, for example:

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

You just have to pass the [: user] (or something else) parameters to User.new () and handle the nested attributes.

0
source

@ Jimworm answer extension:

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

Thus, you pulled the hash from the params hash and collected only the identifiers. Now you can save the user separately, for example:

 @user.update_attributes(params[:user]) 

and add / remove its group identifiers 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 
0
source

Source: https://habr.com/ru/post/1312601/


All Articles