Pyrchev
Pyrchev

Reputation: 21

Ruby on rails attributes validations, methods in model

I have model Project and validates:

validates_presence_of :name, :position, :tel

Project also has another attributes, such as :flag. I want to do so: if you enter :name, :position, :tel, then :flag = true, if one of these attributes are not specified, then :flag = false.

How can I make it and where? In model?

Upvotes: 2

Views: 122

Answers (1)

Yardboy
Yardboy

Reputation: 2805

The way you have that validation declared, the model won't even save unless the user enters all three, so setting flag to false is moot.

That being said, if you want to set an attribute at save time based on the values of other attributes, you can use one of the callback hooks such as before_save.

class Project << ActiveRecord::Base
  before_save :set_flag

  protected

  def set_flag
    self.flag = (self.name.blank? || self.position.blank? || self.tel.blank?) ? false : true
  end
end

Upvotes: 1

Related Questions