2014-05-01 56 views
1

我有一個軌道控制器顯示操作,顯示團隊的父母團隊,團隊的孩子團隊或完整的家庭樹。目前我正在做這個簡單的案例陳述。這是正確的「軌道」方式做或我應該重構?如果是的話,任何建議如何將不勝感激。有許多查詢參數的重構軌道控制器?

if @team= fetch_team 
    case params[:tree] 
    when 'parents' 
    @output = @team.ancestor_ids 
    when 'children' 
    @output = @team.child_ids 
    when 'full' 
    @output = @team.full_tree 
    when nil 
    @output = fetch_team 
    else 
    @output = {message: "requested query parameter: '#{params[:tree]}' not defined"} 
    end 

    render json: @output 
else 
    render json: {message: "team: '#{params[:id]}' not found"}, status: 404 
end 

## 

def fetch_team 
Team.find_by(name: params[:id]) 
end 

回答

4

我會的情況下移動到其自己的方法對你的團隊模式。

class Team 
    def tree(type) 
    ... 
    end 
end 

然後在您的控制器,你可能只是有以下

if @team = fetch_team 
    @output = @team.tree(params[:tree]) 
    render json: @output 
else 
    render json: {message: "team: '#{params[:id]}' not found"}, status: 404 
end 
+1

這是RAILS WAY爲此+1 – HackerKarma

1

你可以寫

if @team = fetch_team 
    @output = case params[:tree] 
      when 'parents' then @team.ancestor_ids 
      when 'children' then @team.child_ids 
      when 'full' then @team.full_tree 
      when nil then @team 
      else {message: "requested query parameter: '#{params[:tree]}' not defined"} 
      end 

    render json: @output 
else 
    render json: {message: "team: '#{params[:id]}' not found"}, status: 404 
end 
+0

第二前,我看到'@team == fetch_team' –

+2

好像你在這個例子中兩次調用fetch_team,如果params [:tree]是否爲零? '當nil然後fetch_team' =>不應該只是'當nil然後@團隊'(它已經設置較早)。我意識到這是最初的例子,但它是一個進一步的編輯。 –

+0

@KurtFunai Overlooked ...謝謝 –