refactor rails控制器有多个查询参数?

时间:2014-05-01 18:54:32

标签: ruby-on-rails ruby controllers

我有一个rails控制器show动作,显示团队的父母团队,团队的子团队或完整的家族树。目前我这样做是一个简单的案例陈述。这是正确的“轨道”方式吗或我应该重构?如果是的话,任何关于如何被赞赏的建议。

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

2 个答案:

答案 0 :(得分: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 :(得分: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