简体   繁体   English

将方法合并到link_to rails 3

[英]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 然后,我有一个名为worldrecipes的单独控制器,其中每个国家/地区名称都有一个动作

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? 我是Rails的新手,我不确定要阅读哪些资源来实现此目的,最好有一种方法可以通过这种逻辑,然后在模块中使用该方法?

a) I would advise you not to have an action per country in your routes as that will really clutter your routes.rb. a)我建议您不要对您的路线中的每个国家/地区采取行动,因为这确实会使您的route.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. 因此,您可以拥有如下网址:/ world / germany,/ world / france但是它们都应该在控制器中调用相同的动作。

b) link_to takes 2 parameters. b) link_to接受2个参数。 First the title to be displayed and the second parameter is the url. 首先是要显示的标题,第二个参数是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 . 现在,您只需要为country_worldrecipes_path定义正确的路由即可。有关路由的更多信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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