验证关联模型的特定属性

时间:2011-12-08 05:47:54

标签: ruby ruby-on-rails-3 validation ruby-on-rails-3.1

验证关联模型属性的最简单的方法是什么?

Item
  belongs_to :user
  validates_presence_of :user
  # AND the "is_photographer" column for that user must be true

User
  has_many :items
  # can be a regular user or a photographer

1 个答案:

答案 0 :(得分:5)

validate :user_is_photographer, :if => :user

def user_is_photographer
  errors.add(:user, "should be a photographer") unless user.is_photographer
end