2

I am making my first app in Ruby on Rails 3.1....Do I have these relationships setup correctly? Essentially, a student/client will be able to login and rate a teacher. A client can have many teachers and a teacher can have many clients. Each client can create a rating for a particular teacher (a teacher can't rate clients). Ratings are optional.

I intend to be able to display a teacher's ratings from various clients and also allow clients to login and rate all the teachers they've had.

class Client < ActiveRecord::Base
  has_many :ratings
  has_and_belongs_to_many :teachers
end

class Teacher < ActiveRecord::Base
  has_many :ratings
  has_and_belongs_to_many :clients
end

class Rating < ActiveRecord::Base
  belongs_to :teacher
  belongs_to :client
end

1 Answers1

4

I'd say that the usage of has_and_belongs_to_many should be used when you only have a database table and not a Rails model to join the models. In your case, since you do have a model called Rating then I'd say it is better to use has_many, :through.

To accomplish that, change your Teacher and Client models to look like this:

class Client < ActiveRecord::Base
  has_many :ratings
  has_many :teachers, :through => :ratings
end

class Teacher < ActiveRecord::Base
  has_many :ratings
  has_many :clients, :through => :ratings
end

The Rating model does not need any changing.

DanneManne
  • 21,107
  • 5
  • 57
  • 58
  • Thank you, I think I was having trouble because I didn't think you could use has_many :through because there's a chance a client may not rate the teacher, but I see the error in my thinking. –  Dec 15 '11 at 04:43