# Habtm + accepts\_nested\_attributes\_for

**URL:** <https://www.ruby-forum.com/t/habtm-accepts-nested-attributes-for/189350>\
**Category:** Rails\
**Created:** [May 29, 2010, 9:52am UTC](https://www.ruby-forum.com/t/habtm-accepts-nested-attributes-for/189350 "2010-05-29T09:52:35Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Brewster](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ac8455/32.png) [@Brewster](https://www.ruby-forum.com/u/Brewster)\
**Post date:** [May 29, 2010, 9:52am UTC](https://www.ruby-forum.com/t/habtm-accepts-nested-attributes-for/189350/1 "2010-05-29T09:52:35Z")

</div>

so i have read conflicting information about this, some seem to pull  
it off, some say its impossible, but here is what i am trying to  
accomplish.  
i am using authlogic w/ lockdown, and when i create a new user, i want  
to add an entry into the user\_groups\_users join table with the new  
user id, and a group id i pass it. i have tried several variations,  
but here is what i ended up with (edited down to only pertinent info).

User model

```auto
class User < ActiveRecord::Base
  has_and_belongs_to_many :user_groups
  accepts_nested_attributes_for :user_groups
end
```

UserGroup model

```auto
class UserGroup < ActiveRecord::Base
  has_and_belongs_to_many :users
end
```

users\_controller

```auto
def new
  @user = User.new(:user_group_ids => params[:group]) # gets
passed in from /users/new?group=1
  @user.user_groups.build #i have tried with and without this.
with it, i get duplicate ID fields in my view
  end
```

view form (haml)

```auto
- form_for @user do |f|
    - f.fields_for :user_groups do |g|
      = g.text_field :id
```

if i fill out all the required fields, the user fields are saved, but  
no user\_groups\_users entry is made  
if i sumbit the form with just the user\_groups\_user id, the field  
dissapears, but in my params, i see

```auto
    user: !map:HashWithIndifferentAccess
      user_groups_attributes: !map:HashWithIndifferentAccess
        "0": !map:HashWithIndifferentAccess
          id: "1"
```

i admit, i am a r00bie, so maybe i am going about this entirely  
wrong. but can anyone offer any input?

thanks
