2015-11-06 92 views
1

首先我要使用Psql,如果有幫助,可能沒有關係。使用三個參數連接兩個表的導軌

我有兩個表,(他們有插圖中模型的has_many)

# models 
RegUser(id, Email, Name) 
Booking(id , Event_id, Reg_user_id) 

我如何去了解這兩個連接在一起,以便查看事件40時,註冊用戶針對該事件將顯示,其基本上都是從經過的PARAMS連接兩個兩個表一起(我相信!)

繼承人我在過去

@reg_usr = RegUser.where(event_id: params[:id]) 

使用的代碼我們感動將event_id分配給另一個表並將其從註冊表中刪除。

+0

創建爲reg_users您的活動模型的has_many關係,所以像: '的has_many: reg_users,通過:預訂' – Doctor06

回答

1

你應該有如下關係:

class Event < ActiveRecord::Base 
    has_many :bookings 
    has_many :reg_users, through: :bookings 

class RegUser < ActiveRecord::Base 
    has_many :bookings 
    has_many :events, through: :bookings 

class Booking < ActiveRecord::Base 
    belongs_to :event 
    belongs_to :reg_user 

然後你就可以簡單地做:

@event = Event.find(params[:id]) 
@reg_users = @event.reg_users # returns the reg_users associated to the Event 
+1

也許值得一提的是,如果你打算枚舉記錄並使用來自reg_users的屬性,以防止出現N + 1問題,請使用includes。 –