【问题标题】:Rails URL helper for sorting filters用于排序过滤器的 Rails URL 助手
【发布时间】:2014-04-04 12:22:50
【问题描述】:

我有一个表 Companies 字段为 city_id。我需要按城市对公司进行分类。接下来我做:

# companies_controller.rb
def sort_by_city
  @cities = City.joins(:company).uniq
  @companies = Company.where("city_id = ?", params[:city_id])
  render 'index'
end

# routes.rb:
get '/companies/city/:city_id', to: 'companies#sort_by_city'

在 index.html.erb 中,我尝试为此过滤器创建链接:

<% @cities.each do |city| %>
  <li><%= link_to city.name, UNKNOWN_path(city.id) %> (<%= city.companies_count %>) 
<% end %>

我想要这样的链接:“www.site.com/companies/city/23” 我必须写什么而不是 UNKNOWN_path?或者我之前做错了什么(在控制器或 routes.rb 中)?

【问题讨论】:

    标签: ruby-on-rails sorting ruby-on-rails-4 view-helpers


    【解决方案1】:

    您可以使用as 选项为您的路线命名:

    例如:

    get '/companies/city/:city_id', to: 'companies#sort_by_city', as: 'companies_city_sort'
    

    然后使用

    companies_city_sort_path
    

    另外,看看resourceful routing,可能会更适应。

    【讨论】:

    • 非常感谢!仅在今天,我才阅读了 3 次以上的 guid“资源路由”。但我现在真的很菜鸟。感谢您的帮助!
    【解决方案2】:

    如果您在终端中输入rake routes,您可以找到当前路径的名称。

    只需查找列出companies#sort_by_city 的行。

    【讨论】:

    • 我看到了companies#sort_by_city,但是我不知道如何使用这些知识
    • 在这一行的左边有指定的路径名​​。你只需要附加_path
    • 在`GET /companies/city/:city_id(.:format) Companies#sort_by_city`之前为空
    • 好的,那么您必须使用as: ... 指定它。但通常查看rake routes 输出通常会有所帮助。
    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 2021-01-11
    • 2012-12-07
    • 1970-01-01
    • 2020-11-11
    • 2022-08-20
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多