简体   繁体   中英

incorporate a method into link_to rails 3

I am building a simple recipe app. I have a method that returns a list of countries in order of most popular

 class Country < ActiveRecord::Base

def self.top_countries
joins(:recipes).
  select('countries.*, count(*) AS recipes_count').
  group('countries.id').
  order('recipes_count DESC')
end

I then output this in the view like so

<% @toprankingcountry.each do |r|%>
 <ul>
 <li><%= link_to r.name %></li>
</ul>

So this just lists all my results

I then have a separate controller called worldrecipes with an action for each country name

What I want to do is link to the specific action for that country (the action will be named the same as the country)

Being new to rails I am not sure on what resources to read to achieve this, would it be better to have a method to go through this logic and then use the method within the block?

a) I would advise you not to have an action per country in your routes as that will really clutter your routes.rb. You can define wildcards and parameters as part of your route, but only one action should handle the different countries.

So you can have urls like this: /world/germany, /world/france But they should all call the same action in your controller.

b) link_to takes 2 parameters. First the title to be displayed and the second parameter is the url.

So you could link to those top ranked countries like this:

<li><%= link_to r.name, country_worldrecipes_path(r) %></li>

Now you only have to define the correct routes for country_worldrecipes_path For more info on routing look here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM