在我的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_ids
会在数组中发布。
有人可以帮忙吗?
答案 0 :(得分: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