I have a model that has a boolean called draft
I want to validate presence of fields only if draft == false.
my model
if self.draft == false
validates :name, :presence => true, :length => { :maximum => 45 }
validates :description, :presence => true
validates :blurb, :presence => true, :length => { :maximum => 175 }
validates :category_id, :presence => true
validates :location_id, :presence => true
validates :goal, :presence => true
else
end
in my controller
def new
@item.new(:draft => false) || @item.new(:draft => true)
def create
if params[:commit] == "Create Item"
@cause = Item.new(params[:item], :draft => false)
elsif params[:commit] == "Save Changes"
@cause = Item.new(params[:item], :draft => true)
end
It completely ignores my if statement and validates anyways whether it's true or not upon clicking Save Changes.
Suggestions would be greatly appreciated.
A conditional validation looks like below
validates :name, :presence => true, :length => { :maximum => 45 }, :if => :draft_is_false?
private
def draft_is_false?
draft == false
end
Similarly, you can perform conditional validations on other fields and these can be grouped as well. Go through the Conditional Validations sections on Ruby on Rails guides.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With