Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 Validate presence based off boolean

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.

like image 778
kaigth Avatar asked Dec 10 '25 21:12

kaigth


1 Answers

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.

like image 52
Kulbir Saini Avatar answered Dec 14 '25 10:12

Kulbir Saini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!