# Hatbm relationship can edit, but not create

**URL:** <https://www.ruby-forum.com/t/hatbm-relationship-can-edit-but-not-create/178150>\
**Category:** Rails\
**Created:** [October 29, 2009, 9:50pm UTC](https://www.ruby-forum.com/t/hatbm-relationship-can-edit-but-not-create/178150 "2009-10-29T21:50:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ian](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/bb73d2/32.png) [@ian](https://www.ruby-forum.com/u/ian)\
**Post date:** [October 29, 2009, 9:50pm UTC](https://www.ruby-forum.com/t/hatbm-relationship-can-edit-but-not-create/178150/1 "2009-10-29T21:50:03Z")

</div>

Hey all,

Following this Railscast ([#17 HABTM Checkboxes - RailsCasts](http://railscasts.com/episodes/17-habtm-)  
checkboxes) I have a set up a form with checkboxes that work great for  
updating records in a hatbm relationship.

But it only works if I’m doing an update to an existing record. When I  
try to create, I get a validation error.

In my app I have Sessions which can have many Learners. In the Session  
edit/create form there’s a list of all the Learners with check boxes  
for selecting them.

I can edit a Session and check/uncheck Learners and the changes are  
saved. When I create a new session, I get a “Learners is invalid”  
validation error.

This is probably happening because the Learner ids can’t be saved into  
the Learners\_Sessions table without a session id, and the the session  
id isn’t created until save. So when I do this:

def create  
@session = @user.project.sessions.new(params[:session])  
if @session.save  
…

it throws out the validation error.

Any ideas on how I can work around this? I could create a bare-bones  
Session object, save it and then update it with the full params, but  
that seems inelegant. I figure there has to be a better solution, I  
just don’t know what it is.

Thanks,

Ian
