I know you can do:
validates :cat_no, :presence => true, :on => :create
I have a custom action:
def approve
@product = Product.find(params[:id])
@product.update_attribute :approved, true
redirect_to product_path(@product)
end
And i’d like to do:
validates :cat_no, :presence => true, :on => :approve
This doesn’t seem to work. Is there a simple way of doing this?
I think you’re misunderstanding the idea of validations. Validations are triggered by changes to the model (via
save,createorupdate), not by controller actions, so it doesn’t make sense in your case to have yourapprovedaction trigger a validation.Looking at your code, it seems to me what you really want to do is run a validation on
cat_nowhen the model is updated, on the condition that the value ofapprovedhas just becometrue(i.e. line 2 of yourapproveaction where you have@product.update_attribute :approved, true).I think the code below should achieve that:
UPDATE:
In retrospect, the validation above is probably more permissive than what you’d actually want to have. If you have an approved record and you change
cat_notonil, it will validate becauseapprovedhas not changed (sochanged.include?("approved")will evaluate tofalse).More likely this is what you actually want: