11

I need to override the name of a relation, here is my model:

class User < ActiveRecord::Base

  has_many :class_rooms_member_ships

  has_many :class_rooms
  has_many :class_rooms, :through=> :class_rooms_member_ships

end

now, I need another name to use when I want to get class_rooms :through=> :class_rooms_member_ships

how can I achieve this:

user.class_rooms
user.class_rooms_through

Any idea ?

simo
  • 23,342
  • 38
  • 121
  • 218
  • Have you checked http://stackoverflow.com/questions/1163032/rails-has-many-with-alias-name? – zsquare May 31 '12 at 04:50
  • but, my case is a little bit different, I am using has_many through – simo May 31 '12 at 10:11
  • The question's title is misleading in a way. Strictly speaking you are not asking for an alias as stated in the question. Because that would mean that the association would still have to be accessible by its original name. Instead you are asking for a way to define the name of the association. The answer for the question in the title is probably `alias_attribute`. – Andreas Baumgart Jul 15 '17 at 16:46

2 Answers2

14
has_many :classrooms_though_memberships, :through=> :class_rooms_member_ships, 
                                     :class_name => 'ClassRoom', 
                                     :foreign_key => 'class_room_id',
                                     :source => :class_room

This should work.

Seb Jacobs
  • 156
  • 3
0

Something like this should work:

has_many :classrooms_though_memberships, :through=> :class_rooms_member_ships, 
                                         :class_name => 'ClassRoom', 
                                         :foreign_key => 'class_room_id'
Chris Mohr
  • 3,639
  • 1
  • 13
  • 9
  • I tried it, but, I've got this error: ActiveRecord::HasManyThroughSourceAssociationNotFoundError in ClassRoomsMemberShipsController#index Could not find the source association(s) :classrooms_though_membership or :classrooms_though_memberships in model ClassRoomsMemberShip. Try 'has_many :classrooms_though_memberships, :through => :class_rooms_member_ships, :source => '. Is it one of ? – simo May 31 '12 at 09:13