2012-05-31 53 views
9

我需要重寫一個關係的名字,這裏是我的模型:rails,如何在模型中混淆關係?

class User < ActiveRecord::Base 

    has_many :class_rooms_member_ships 

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

end 

現在,我需要另一個名字時,我想class_rooms :through=> :class_rooms_member_ships

我怎麼能做到這一點使用方法:

user.class_rooms 
user.class_rooms_through 

任何想法?

+0

你檢查了http://stackoverflow.com/questions/1163032/rails-has-many-with-alias-name? – zsquare

+0

但是,我的情況有點不同,我使用has_many通過 – simo

+0

仍然是同樣的事情。 – zsquare

回答

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

這應該工作。

+0

確切地說,它工作正常,似乎源丟失,謝謝 – simo

+0

'class_name'和'foreign_key'不應該是必要的,'source'指定關係名稱。 – elactic

0

像這樣的東西應該工作:

has_many :classrooms_though_memberships, :through=> :class_rooms_member_ships, 
             :class_name => 'ClassRoom', 
             :foreign_key => 'class_room_id' 
+0

我試了一下,但是,我得到這個錯誤: 的ActiveRecord :: HasManyThroughSourceAssociationNotFoundError在ClassRoomsMemberShipsController#指數 找不到源協會(S):classrooms_though_membership或:classrooms_though_memberships模型ClassRoomsMemberShip。嘗試'has_many:classrooms_though_memberships,:through =>:class_rooms_member_ships,:source =>'。它是其中之一嗎? – simo