legendary_rob
legendary_rob

Reputation: 13012

Rails polymorphic aliased associations

I would like to try set up this association:

# app/models/course.rb
class Course < ActiveRecord::Base
  belongs_to :subjectable, polymorphic: true
end

# app/models/student.rb
class Student < ActiveRecord::Base
  has_many :courses, as: :subjectable
end

# app/models/campus.rb
class Campus < ActiveRecord::Base
  has_many :courses, as: :subjectable
end

But this did not read very well in the code.

#this seems fine
campus = Campus.last
campus.courses 

#this dosent make much sense gramatically 
student = Student.last
student.courses

Campuses offer Courses, but Students don't have courses they have subjects. Now they are the same thing under the covers they just don't read well.

How could I get it so that student.subejects would yield the same result as student.courses?

Upvotes: 1

Views: 53

Answers (1)

Thomas
Thomas

Reputation: 1633

You can name the association as you want, you don't have to mach the associated class.

In this case, you have to tell ActiveRecord what the pointed class is :

# app/models/student.rb
class Student < ActiveRecord::Base
  has_many :subjects, as: :subjectable, class_name: 'Course'
end

Upvotes: 1

Related Questions