开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜