HABTM - update with no values selected

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

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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs