通过自定义控制器操作有条件地路由 rails root 呈现问题

Render problems with conditionally routing rails root through custom controller action

我正在尝试有条件地路由两个不同的控制器操作。我已经创建了 RoutesController#root 并从 routes.rb 发送了 root,但是无论我在根方法中写了什么,应用程序只想找到一个要渲染的根模板。

我想要实现的是:

  1. 用户请求‘/’
  2. 用户被强制登录
  3. 成功登录后,如果 current_user.company.present?(current_user 应该在路由控制器中可用,对吧?)然后渲染报价#new
  4. 否则,如果没有公司则呈现 Companies#new

我遇到了缺少模板的错误;

Missing template companies/1/quotes/new.1 with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * "app/views"

我希望它在 app/views/quotes/new 中搜索,我做错了什么?

RoutesController.rb

class RoutesController < ActionController::Base
  before_filter :authenticate_user!

  def root
    if current_user.company.present? 
      render new_company_quote_path(current_user)# 'quotes#new'
    else
      render new_company_path(current_user) # 'companies#new'
    end
  end
end

routes.rb

root 'routes#root'

render 当您只想 render/display 路径中的特定视图时使用,它不执行任何代码。详细区别见this post.

因此,在您的情况下,它应该是 redirect_to 而不是 render

关于最佳实践,我觉得不错。