2010-06-19 28 views
0

我有一個before_filter來設置一個arel關係,但如果我先調用它的方法,它不喜歡它。它似乎在控制檯中工作正常。我在這裏錯過了什麼?瞭解Arel更好

class TeamsController < ApplicationController 
    before_filter :find_team 

    def show 
    @team.first 
    end 

    private 

    def find_team 
    @team = Team.where(:id => params[:id]) 
    end 
end 
+0

你是否收到錯誤信息? – 2010-06-19 17:16:45

+0

它工作正常,直到我不想迭代對象上有很多集合。我爲[]獲得未定義的方法'任務':ActiveRecord :: Relation – Cameron 2010-06-19 17:31:00

回答

0

您將電話結果丟到first。你想做類似的事情:

 
    def show 
    @team = @team.first 
    end 
0

出現錯誤,我不知道它是否是錯字。

def TeamsController < ApplicationController 

應該

class TeamsController < ApplicationController 

關於這個問題,記得你可以在一個單一的記錄,而不是一個數組迭代任務。 換句話說

@team = Team.where(:id => params[:id]) 

@team.first.tasks # => OK 
@team.tasks # => Not OK, you're trying to call tasks on an Array 
1

where方法返回的關係,而不是一個對象。要獲取對象,請使用first方法從關係中返回一個對象(或nil)。

def find_team 
    @team = Team.where(:id => params[:id]).first 
end 

first方法不更新的關係 - 它返回呼籲的關係時的對象。

+0

那麼,爲什麼在before_filter之後的show方法中調用@ team.first時它不起作用? – Cameron 2010-06-19 22:15:12

+0

因爲,正如我所說的,'first'方法不會更新關係 - 它在關係上調用時會返回一個對象。它*返回*一個對象。當你在示例'show'方法中調用'first'時,你不會對返回的'Team'對象做任何事情,並且'@ team'仍然是一個關係,而不是'Team'對象。 – yfeldblum 2010-06-19 23:44:51