【问题标题】:RAILS: Rendering views from the same controller based on the routeRAILS:基于路由从同一个控制器渲染视图
【发布时间】:2018-03-20 14:52:13
【问题描述】:

我有两条路线(在我的 config/routes.rb 中定义)

match 'compare'     => 'front_office#search_by_id', :via => :get, :as => :front_office_compare
match 'full_report' => 'front_office#search_by_id', :via => :get, :as => :front_office_full_report

我想知道如何告诉我的控制器根据我的路由呈现视图,而不在我的 URL 上添加参数。

基于这个Question&Answer我设法得到我想要的结果

match 'compare'     => 'front_office#search_by_id', :via => :get, :as => :front_office_compare,     :defaults => { :render => 'compare' }
match 'full_report' => 'front_office#search_by_id', :via => :get, :as => :front_office_full_report, :defaults => { :render => 'full_report' }

在我的控制器中,我将我的操作定义为:

  def search_by_id
    render :action => (params[:render] || "full_report")
  end

但这是一个好的做法还是有更好的方法?

【问题讨论】:

  • 这并没有多大意义。为什么不首先将其映射到两个不同的操作?
  • @phoet 因为数据是一样的,只是我们显示它的方式会改变。前任。摘要与详细信息报告。
  • @JudgeProphet 那么我认为您需要根据您的要求更改您的操作名称以使其更有意义。 search_by_id 似乎有点类似于 show 现在的行动。

标签: ruby-on-rails routes


【解决方案1】:

您可以将其编写为:

# config/routes.rb 

get ":category", to: "front_office#search_by_id", as: 'front_office', constraints: {category: /(compare|full_report)/}

上述路由会查找/compare/full_report,这将在front_office 控制器中调用search_by_id 操作。

然后在控制器内部执行以下操作:

def search_by_id
  render params[:category]
end

params[:category] 将保存我们通过 URL 传递的 slug 值

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多