# Validations on array checkbox in Model

**URL:** <https://www.ruby-forum.com/t/validations-on-array-checkbox-in-model/196838>\
**Category:** Rails\
**Created:** [November 7, 2008, 1:51pm UTC](https://www.ruby-forum.com/t/validations-on-array-checkbox-in-model/196838 "2008-11-07T13:51:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![babar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/8c91f0/32.png) [@babar](https://www.ruby-forum.com/u/babar)\
**Post date:** [November 7, 2008, 1:51pm UTC](https://www.ruby-forum.com/t/validations-on-array-checkbox-in-model/196838/1 "2008-11-07T13:51:15Z")

</div>

Hi,

I am using array ‘sub\_id[]’ for multiple checkbox,  
i want to place validations on all array ‘sub\_ids[]’ checbox in model  
just  
like other validations.

\<% for e in @subjects do -%\>  
\<input type=“checkbox” name=“sub\_ids[]” id="\<%= e.id %\>" value="\<%=  
e.id%\>"\<% if @book.subjects.include? e %\> checked=“checked”\<%end%\>\>  
\<%= e.name %\>  
\<% end %\>

MODEL

class Book \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :subjects  
validates\_presence\_of:title  
validates\_numericality\_of:price  
validate :at\_least\_one\_checkbox\_was\_ticked

protected  
def at\_least\_one\_checkbox\_was\_ticked  
unless params[:sub\_ids[]].nil?  
end  
end

end

I’m using only two models book and subject.

thanx in adv.

---

<div class="post-metadata">

**Author:** ![babar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/8c91f0/32.png) [@babar](https://www.ruby-forum.com/u/babar)\
**Post date:** [November 7, 2008, 2:00pm UTC](https://www.ruby-forum.com/t/validations-on-array-checkbox-in-model/196838/2 "2008-11-07T14:00:38Z")

</div>

On 7 Nov 2008, at 12:50, babar wrote:

> %= e.id %\>"\<% if @book.subjects.include? e %\> checked=“checked”\<%end  
> validates\_presence\_of:title  
> validates\_numericality\_of:price  
> validate :at\_least\_one\_checkbox\_was\_ticked
> 
> protected  
> def at\_least\_one\_checkbox\_was\_ticked  
> unless params[:sub\_ids[]].nil?  
> end  
> end

That’s not how you could do it. You don’t validate against  
params[:sub\_ids], you validate against a property of the model (ie  
subjects.size)

Fred
