关联:一对多关系,如何Return从多到一?

Associations: One to Many Relationship, How to Return to the One from Many?

我有一个简单的网站,我在上面展示食谱中的食谱。

每本食谱都有很多食谱。

我的问题:如何 link 用户从菜谱页面返回到正确的菜谱页面?我如何将正在使用 id 4 查看食谱的用户引导回使用 id 2 的食谱?

食谱控制器:

class CookbookController < ApplicationController
    def index
        @cookbooks = Cookbook.all
    end

    def show
    @cookbook = Cookbook.find(params[:id])
    @recipes = @cookbook.recipes
    end
end

配方控制器:

class RecipesController < ApplicationController
  def show
    @recipe = Recipe.find(params[:id])
  end
end

食谱模型:

class Cookbook < ActiveRecord::Base
  has_many :recipes
end

配方模型:

class Recipe < ActiveRecord::Base
  belongs_to :cookbook
end

路线:

Rails.application.routes.draw do
  get '/' => redirect('/cookbooks')

  get '/cookbooks' => 'cookbooks#index'
  get '/cookbooks/:id' => 'cookbooks#show', as: :cookbook

  get '/recipe/:id' => 'recipes#show', as: :recipe
end

到目前为止我一直在使用:

<%= link_to "Back", :back %>

但这不是长久之计。

我遵循了 Rails 路由指南 here 并尝试了以下操作(并收到以下错误):

<%= link_to "Back", cookbook_path(@cookbook) %>

No route matches {:action=>"show", :controller=>"cookbooks", :id=>nil} missing required keys: [:id]

<%= link_to "Back", cookbook_path(@cookbook.id) %>

undefined method `id' for nil:NilClass

以及其他提出 errors/exceptions 或使用食谱 id 而不是食谱 id 的解决方案。

我还尝试允许食谱控制器继承食谱控制器,以便获得食谱的 id

当您尝试将 Cookbook 控制器与 cookbook_path 一起使用时,您走在了正确的轨道上(没有双关语意)。

每个食谱都会存储其各自食谱的 id 以及您在两个模型中定义的一对多关系。

因此,我们可以利用这个简单的 link_to:

<%= link_to "Back", cookbook_path(@recipe.cookbook.id) %>