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 t开发者_如何学Gohese attributes are not specified, then :flag = false.
How can I make it and where? In model?
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
精彩评论