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
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.