Search code examples
ruby-on-railsrubycontrollers

refactor rails controller that has many query parameters?


I have a rails controller show action which shows either the parents teams of a team, the child teams of a team, or the full family tree. Currently I am doing this as a simple case statement. Is this the correct "rails" way to do it or should I refactor? If yes, any suggestions on how would be appreciated.

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

Solution

  • I would move the case into its own method on your Team model.

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

    Then in your controller you could just have the following

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