# Simple and elegant checkboxes with has\_many through impossible?

**URL:** <https://www.ruby-forum.com/t/simple-and-elegant-checkboxes-with-has-many-through-impossible/124005>\
**Category:** Rails\
**Created:** [December 23, 2007, 11:22am UTC](https://www.ruby-forum.com/t/simple-and-elegant-checkboxes-with-has-many-through-impossible/124005 "2007-12-23T11:22:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nowy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/bc8723/32.png) [@Nowy](https://www.ruby-forum.com/u/Nowy)\
**Post date:** [December 23, 2007, 11:22am UTC](https://www.ruby-forum.com/t/simple-and-elegant-checkboxes-with-has-many-through-impossible/124005/1 "2007-12-23T11:22:42Z")

</div>

Hi,

Im currently developing simple website to manage some sort of product.  
Every product has its own product\_categories, so these are related  
with has\_many :through association. product has many product  
categories. im not using habtm, i prefer has\_many through and i can’t  
change it, so habtm is out of scope. quite simple isn’t it ?

Ok, so i tried to make a CRUD for it, you know simple thing like:  
name for a product, and list of checkboxes for product categories.  
when i check some of checboxes, the categories are assigned to my  
product, at least one category checkbox has to be checked  
(validation), nothing special.

I came up with this (based on some articles from this forum):  
[http://pastie.caboo.se/131841](http://pastie.caboo.se/131841)

The whole project is available to download and run on google code:  
[http://glodomor.googlecode.com/svn/trunk/](http://glodomor.googlecode.com/svn/trunk/)

Feel free to post code patches through issue tracker if you want to.  
[http://code.google.com/p/glodomor/issues/list](http://code.google.com/p/glodomor/issues/list)

The code above comes from this forum and i feel it’s rails hacking a  
little bit, and it doesn’t work as it should, here’s why:

Here are my really serious problems:

1. Checkboxes dont remember their state when validation fails. For  
example, when i check two of them, and hit submit (leaving name  
textfield empty which causes validation to fail) i get the view again,  
but checkboxes i checked are reset to the initial state. really  
frustrating.

2. My unit tests for Product model does not pass. Why ? Because im  
doing validation through custom validate method, which checks  
product\_category\_ids attribute (this is attribute generated by rails  
automaticaly right ? ) which is simply view related, not model. so  
when i create in my test Product and assign category to it, it fails  
because im assigning product\_category to my product, not  
product\_category\_ids…

Question is simple, how do i do has\_many with checkboxes so that works  
like any other simple field of my model like name where it remember  
state between postbacks and does all validations i want  
(validates\_presence\_of) ?

Best regards
