link_to 相同的动作,不同的条件

link_to same action, different conditions

我有一个食谱模型 has_many 通过关联(类别,分类)。

在主页上,我列出了所有类别,我想在每个类别上创建一个 link_to,链接到包含属于该类别的所有食谱的页面。

最好的方法是什么?

我可以根据某些条件 Recipe.where(category: "something") 为配方控制器上的每个类别创建不同的操作,但这也需要不同的视图。

是否有更好的方法(使用更好的 RESTful 方法)来实现这一点?

谢谢。

为此使用嵌套资源:

resources :categories do
  resources :recipes
end

这将生成类似 /categories/:category_id/recipes 的路由,这将是食谱的 index 操作,但在参数中具有类别 ID

您也可以使用 slug 作为类别而不是数字 ID。

执行此操作的 "correct" 方法是使用 nested resources 为您提供指定 "parent" 模型的方法(在您的情况下 Category):

#config/routes.rb
resources :categories do
   resources :recipes, only :index
end

#app/controllers/recipes_controller.rb
class RecipesController < ApplicationController
   def index
       @category = Category.find params[:category_id] if params[:category_id]
       @recipes  = @category ? @category.recipes : Recipe.all
   end
end

以上将允许您 link 以下内容:

#app/views/categories/index.html.erb
<% @categories.each do |category| %>
   <%= link_to "Recipes", [category, :recipes] %>
<% end %>

这将允许您使用以下内容填充 recipes#index 操作:

#app/views/recipes/index.html.erb
<% @recipes.each do |recipe| %>
   <%= recipe.title %>
<% end %>