如何在Rails中验证组(集合)的元素是否为每个父对象唯一?

时间:2012-08-23 03:46:02

标签: ruby-on-rails validation validates-uniqueness-of

我的应用程序要求Courses Projects Groups Users. users我需要确保projectclass Group < ActiveRecord::Base attr_accessible :name, :project_id #has_and_belongs_to_many fields attr_accessible :user_ids has_and_belongs_to_many :users belongs_to :project, :inverse_of => :groups validates :name, :project_id, :presence => true validates :user_ids, :uniqueness => { :scope => :project_id, :message => "Users can only be in one group per project." } end 不会出现一次以上ActiveAdmin.register Group do form do |f| f.inputs do f.input :name f.input :users, :as => :check_boxes f.input :project end f.buttons end end 我认为我可以通过Rails验证来实现,但我所拥有的似乎并不想工作。任何人都可以帮我解决这个问题吗?

以下内容给了我:

  Admin中的

NoMethodError :: GroupsController #create
  未定义的方法`text?'为零:NilClass

{{1}}

ActiveAdmin Group对象:

{{1}}

1 个答案:

答案 0 :(得分:0)

我会尝试

Course
  has_many :projects

Project
  has_many :groups
  has_many :users, :through => groups
  validates uniqueness_of :user

User
  has_many groups 
  has_many projects, :through => :groups

Group
  belongs_to :project
  belongs_to :group

# I stay away from has_and_belongs_to_many, not flexible later.