SitePoint Sponsor |
|
User Tag List
Results 1 to 1 of 1
-
Feb 3, 2008, 11:50 #1
- Join Date
- Jul 2001
- Location
- Los Angeles
- Posts
- 50
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
update_attributes updates habtm even if validation fails
I'm stuck on something that I've searched high and low for but couldn't find a solution. I basically have two models with HABTM relationships:
Code:class Category < ActiveRecord::Base has_and_belongs_to_many :products ... end
Code:class Product < ActiveRecord::Base has_and_belongs_to_many :categories def validate if category_ids.blank? errors.add_to_base("You must select at least one category for this product.") end end end
Here's the update method in the products controller:
Code:def update params[:product][:category_ids] ||= [] @product = Product.find(params[:id]) respond_to do |format| @product.attributes = params[:product] if @product.valid? flash[:notice] = 'Product was successfully updated.' format.html { redirect_to(@product) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @product.errors, :status => :unprocessable_entity } end end end
Code:@product.attributes = params[:product]
Any ideas how to validate first before anything is updated? I'd really appreciate any help!
Bookmarks