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 ... endI followed the screencast and code here: http://railscasts.com/episodes/17 to list out the categories in my views. The screencast doesn't cover any validation but I want to make sure that at least one category is always selected which is why I added the custom validate method. The new view and create method works perfectly (the user receives an error if s/he doesn't select any categories). However, if the user decides to edit the product and deselects all the categories in the edit view, Rails appears to update the categories_products table (the join table) BEFORE running any validation. The validation fails but it's too late! The categories are already deleted.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:
I realize that the above code won't save the product but I decided to assign the attributes directly instead of using update_attributes to demonstrate my issue. Anyway, whenCode: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 endexecutes, Rails immediately the following SQL statement "DELETE FROM categories_products WHERE product_id = 2 AND category_id IN (1,2)" before I can even validate anything. The same thing happens with update_attributes; the categories_products table is updated and then Rails attempts to validate the product model. I basically think I'm running into the Rails bug described here: http://dev.rubyonrails.org/ticket/9931Code:@product.attributes = params[:product]
Any ideas how to validate first before anything is updated? I'd really appreciate any help!




Bookmarks