1

在我的 Rails 应用程序中,我有has_many through两个模型之间的关系,因此我正在创建这样的新对象:

Project.new(:name => 'Test', :person_ids => [1, 2, 3])

验证模型中的那些的好方法是什么person_ids

这是我到目前为止所拥有的:

class Project < ActiveRecord::Base

  has_many :people_projects 
  has_many :people, :through => :people_projects 

  validates :person_ids, inclusion => { :in => lambda { |x| x.valid_people } }

  def valid_people
    user.people.map(&:id)   
  end    

end

但是,这不起作用,因为person_idsget 发布在数组中。

有人可以帮忙吗?

4

1 回答 1

2

使用自定义验证方法,例如

class Project < ActiveRecord::Base
  validate :valid_people

  def valid_people
    people = user.people.pluck(:id)
    if person_ids.blank? || (person_ids - people).any?
      errors.add(:person_ids, "Please add real people")
    end
  end    

end
于 2013-10-28T20:49:31.350 回答