سؤال

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
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

You could write

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top