I have a table Companies with field city_id. I need in sorting companies by cities. I do next:

# 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'

and in index.html.erb I try make links for this filter:

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

I want links like this: "www.site.com/companies/city/23" What I must write instead of UNKNOWN_path? Or I do something wrong before (in controller or in routes.rb)?

有帮助吗?

解决方案

You can give a name to your route with the as option :

For example :

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

And then use

companies_city_sort_path

Also, have a look at resourceful routing, it may be more adapted.

其他提示

If you type rake routes in your terminal you can find the name of the current path.

Just look for the line where companies#sort_by_city is listed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top