# Has\_and\_belongs\_to\_many form with check\_box

**URL:** <https://www.ruby-forum.com/t/has-and-belongs-to-many-form-with-check-box/194402>\
**Category:** Rails\
**Created:** [September 3, 2010, 8:37pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-form-with-check-box/194402 "2010-09-03T20:37:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gregm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/bc79bd/32.png) [@gregm](https://www.ruby-forum.com/u/gregm)\
**Post date:** [September 3, 2010, 8:37pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-form-with-check-box/194402/1 "2010-09-03T20:37:34Z")

</div>

Hi,

I have 2 models, user and project.  
When I edit my profile I wan’t to check the projects I wan’t to follow.  
So here is my code:

\<% form\_for @user do |f| %\>  
…  
\<% for project in @projects %\>  
\<% fields\_for “user[project\_attributes][]”, project do  
|project\_form| %\>

-   
\<%= project\_form.check\_box “checked”, {:checked =\>  
@user.project\_ids.include?(project.id)} %\>\<%= project.name  
%\>  
  
\<% end %\>  
\<% end %\>  
…  
\<% end %\>

I think the form is correct but the model and controller part is not  
very clear…

Here is the log:  
“user”=\>{“project\_attributes”=\>{“1”=\>{“checked”=\>“1”},  
“2”=\>{“checked”=\>“1”}, “3”=\>{“checked”=\>“0”}, “4”=\>{“checked”=\>“0”},  
“5”=\>{“checked”=\>“0”}}, “password\_confirmation”=\>"[FILTERED]",  
“password”=\>"[FILTERED]"

The project\_attributes is really messy and I have to parse the hash to  
get selected projects.

There must be a cleaner way??

Greg

---

<div class="post-metadata">

**Author:** ![gregm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/bc79bd/32.png) [@gregm](https://www.ruby-forum.com/u/gregm)\
**Post date:** [September 4, 2010, 12:37am UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-form-with-check-box/194402/2 "2010-09-04T00:37:14Z")

</div>

You seen this?

> **[\#17 HABTM Checkboxes - RailsCasts](http://railscasts.com/episodes/17-habtm-checkboxes)**
>
> Short Ruby on Rails screencasts containing tips, tricks and tutorials. Great for both novice and experienced web developers.

[http://asciicasts.com/episodes/17-habtm-checkboxes](http://asciicasts.com/episodes/17-habtm-checkboxes)

Seems like you would want to use something like:  
@product.categories.include?(category)

except you would be like @user.projects.include?(project)
