【问题标题】:Render problems with conditionally routing rails root through custom controller action通过自定义控制器操作渲染有条件地路由 rails root 的问题
【发布时间】:2017-07-17 09:44:18
【问题描述】:

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

我想要实现的是:

  1. 用户请求“/”
  2. 用户被推送登录
  3. 成功登录后如果current_user.company.present?(current_user 应该在Routes 控制器中可用,对吧?)然后渲染Quotes#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'

【问题讨论】:

  • 您是否尝试过给您的控制器和操作起一个不同的名称?因为它们似乎是保留关键字..
  • 尝试将exit 放入根方法中。比你能知道它实际上是否进入根方法。
  • 改用redirect_to
  • 应该是redirect_to不渲染。
  • ha :) Farhan 刚刚把你拉到了帖子上,所以我想公平地说我应该接受他的回答,但他似乎已经下线了,所以如果他不回答,让我们给他 10 分钟那么没有问题我会接受你的??????????。 Vishal 再次给你点赞,;),下一次,感谢你的帮助。

标签: ruby-on-rails routing root


【解决方案1】:

render 在您只想从路径渲染/显示特定视图时使用,它不执行任何代码。详细区别见this发帖。

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

关于最佳实践这件事,我觉得很好。

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 2010-09-25
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多