Forum: Ruby on Rails how to perform validation prior to creating a new association between records?

Posted by Cathal O'Riordan (coriordan)
on 2013-01-03 16:15
(Received via mailing list)
Hi,

I'm trying to figure out the correct "Rails" way to perform validation
prior to creating a new assocation between my models. Here's the models:

class User < ActiveRecord::Base

  has_and_belongs_to_many :roles
  has_many :instructorships
  has_many :instructed_courses, :through => :instructorships, :source =>
:course

class Course < ActiveRecord::Base

  has_many :instructorships
  has_many :instructors, :through => :instructorships, :source =>
:instructor

class Instructorship < ActiveRecord::Base
  belongs_to :instructor, :class_name => 'User', :foreign_key => 
'user_id'
  belongs_to :course

I'm trying to introduce a validation whereby only user objects with a 
role
of 'instructor' can be assigned as an instructor on a course.

Firstly, where would this validation go? On the association model? And
secondly, what is the right way to set this up?

thanks for your help,
Cathal.
Posted by Dheeraj Kumar (Guest)
on 2013-01-03 19:58
(Received via mailing list)
The validation would go in the Instructorship model.

You'll need a custom method, like so: 
http://edgeguides.rubyonrails.org/active_record_va...

--
Dheeraj Kumar
Posted by Cathal O'Riordan (coriordan)
on 2013-01-04 10:21
(Received via mailing list)
Thanks Dheeraj :)
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.