2013-02-27 60 views
1

我有一個名爲「匹配」模式,一個名爲「賭注」訪問軌包括具有的has_many

class Match < ActiveRecord::Base 
    ... 
    has_many :bets 
end 

模型和我的模型投注:

class Bet < ActiveRecord::Base 
    attr_accessible :match_id, :user_id, :bet 
    ... 
    belongs_to :match 
    belongs_to :user 
end 

我用下面的代碼選擇一些比賽和用戶的賭注:

@matches = Match.includes(:bets).where("bets.user_id = ? or bets.user_id is NULL", @user.id) 

如何使用此查詢訪問用戶下注?

使用這不起作用:

@matches.each do |match| 
    match.bet.bet 
    ... 

如何訪問內部比賽的賭注屬性?

謝謝!


試圖@sevenseacat的答案與此代碼:

@user ||= User.find_by_id(params[:user_id]) if params[:user_id] 

    if @user 
    @matches = Match.includes(:home_team, :away_team, :bets).where("bets.user_id = ? or bets.user_id is NULL", @user.id) #.group_by{ |match| match.date.strftime("%d/%m/%y")} 

    @matches.each do |match| 
     match.bets.each do |bet| 
     bet.bet 
     end 
    end 
    end 

我已經改變了它match.bets.first(我只有1個賭注爲每match_id和USER_ID所以它的工作原理)。

回答

2

您可以通過在您的區塊內簡單地使用match.bets來訪問每場比賽的投注。

如果您想迭代這些投注,請使用另一個each

+0

謝謝您的回答也許不錯。每個用戶只能爲一場比賽投注一次。有一種方法可以讓用戶匹配。 – 2013-02-27 14:01:08

+0

通過你的代碼,一場比賽仍然有很多投注,但'match.bets'只包含正確的投注。 – sevenseacat 2013-02-27 14:02:11

+0

此代碼正在打印匹配對象,而不是投注。 '@matches.each do | match | match.bets.each do | bet | bet.bet end end' – 2013-02-27 14:04:50

0

@sevenseacat是正確
@match.bet.each { |bet| bet.attr }