2014-05-01 58 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 ...谢谢 –