ruby-on-rails - 重构具有许多查询参数的 Rails Controller ?

标签 ruby-on-rails ruby controllers

我有一个 Rails Controller 显示操作,它显示一个团队的父团队、一个团队的子团队或完整的家谱。目前我正在做一个简单的案例陈述。这是正确的“rails ”方式还是我应该重构?如果是,将不胜感激。

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

最佳答案

我会在您的团队模型中将案例移动到它自己的方法中。

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

然后在你的 Controller 中你可以有以下内容

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

关于ruby-on-rails - 重构具有许多查询参数的 Rails Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23414508/

相关文章:

html - 有没有办法在 text_field_tag 上设置必需的属性?

ruby-on-rails - ActiveRecord 范围不起作用

ruby-on-rails - 在 Rails 中的操作之间插入 Controller 操作 - 最佳实践

ruby-on-rails - 铁路应用模型/ Controller 和路线组织

salesforce - 检索 salesforce 实例 URL 而不是 Visualforce 实例

ruby-on-rails - ActiveRecord 查询中的 "includes"和 "joins"有什么区别?

ruby-on-rails - ActiveRecord - "first"中的 "scope"方法返回多条记录

ruby-on-rails - Redis 和 Sidekiq 在 Ubuntu 16.04 上的生产环境中使用 systemd 和 Capistrano 部署

ruby-on-rails - 如何在我的 Controller 规范中获取 view_context 以测试事件模型序列化程序

ruby - 什么是最优雅的 Ruby 语句,可以将字符串中的字符两两分开?