Micah Gideon Modell
Micah Gideon Modell

Reputation: 629

How do I validate that elements of a group (collection) are unique per parent object in Rails?

My app calls for Courses with Projects with Groups with Users. I need to make sure that users never appear more than once per project and I think I can do it with a Rails validation, but what I've got doesn't seem to want to work. Can anyone help me out with this?

The following gives me:

NoMethodError in Admin::GroupsController#create
undefined method `text?' for nil:NilClass

class 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 Group object:

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

Upvotes: 1

Views: 434

Answers (1)

Michael Durrant
Michael Durrant

Reputation: 96484

I would try

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.

Upvotes: 1

Related Questions