# HABTM - update with no values selected

**URL:** <https://www.ruby-forum.com/t/habtm-update-with-no-values-selected/104361>\
**Category:** Rails\
**Created:** [May 17, 2007, 5:21am UTC](https://www.ruby-forum.com/t/habtm-update-with-no-values-selected/104361 "2007-05-17T05:21:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![john\_old](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9f8e36/32.png) [@john\_old](https://www.ruby-forum.com/u/john_old)\
**Post date:** [May 17, 2007, 5:21am UTC](https://www.ruby-forum.com/t/habtm-update-with-no-values-selected/104361/1 "2007-05-17T05:21:18Z")

</div>

I am a rails newbie and I am trying to figure out the best way to solve  
this problem. Here is the code in my controller (the param tag\_ids is a  
series of checkboxes).

1 def update  
2 @blog = Blog.find(params[:id])  
3 if @params[:tag\_ids]  
4 @blog.tags = Tag.find(@params[:tag\_ids])  
5 else  
6 @blog.tags = nil  
7 end  
8 @blog.modified = Time.now  
9 @blog.update\_attributes(params[:blog])  
10 redirect\_to :action =\> ‘show’, :id =\> @blog  
11 end

Tags has\_and\_belongs\_to\_many Blogs. It works fine if I select any of  
the checkboxes in my view, but if I select none, then I get nil errors.  
So the problem is with this line 6. How do I tell the database code  
that there should be no tags and delete all from the database associated  
with this blog? Thanks in advance!

John

---

<div class="post-metadata">

**Author:** ![john\_old](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9f8e36/32.png) [@john\_old](https://www.ruby-forum.com/u/john_old)\
**Post date:** [May 17, 2007, 5:51am UTC](https://www.ruby-forum.com/t/habtm-update-with-no-values-selected/104361/2 "2007-05-17T05:51:02Z")

</div>

try

> 1 def update  
> 2 @blog = Blog.find(params[:id])  
> 3 if @params[:tag\_ids]  
> 4 @blog.tags = Tag.find(@params[:tag\_ids])  
> 5 else  
> 6 @blog.tags = []  
> 7 end  
> 8 @blog.modified = Time.now  
> 9 @blog.update\_attributes(params[:blog])  
> 10 redirect\_to :action =\> ‘show’, :id =\> @blog  
> 11 end

gl

---

<div class="post-metadata">

**Author:** ![john\_old](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9f8e36/32.png) [@john\_old](https://www.ruby-forum.com/u/john_old)\
**Post date:** [May 17, 2007, 5:54am UTC](https://www.ruby-forum.com/t/habtm-update-with-no-values-selected/104361/3 "2007-05-17T05:54:36Z")

</div>

forget what I said use

> > 1 def update  
> > 2 @blog = Blog.find(params[:id])  
> > 3 if @params[:tag\_ids]  
> > 4 @blog.tags = Tag.find(@params[:tag\_ids])  
> > 5 else  
> > 6 @blog.tags.clear  
> > 7 end  
> > 8 @blog.modified = Time.now  
> > 9 @blog.update\_attributes(params[:blog])  
> > 10 redirect\_to :action =\> ‘show’, :id =\> @blog  
> > 11 end
