我需要帮助在我的网络应用中实施和添加收藏夹功能。这是一个食谱应用程序,厨师(用户)可以将其他厨师的食谱保存为“收藏夹”。
在模型级别,我有以下关联:
chef.rb:
has_many :favorites
has_many :recipes, through: :favorites
recipe.rb:
has_many :favorites
has_many :chefs, through: :favorites
favorite.rb:
class Favorite < ApplicationRecord
belongs_to :chef
belongs_to :recipe
end
在迁移文件中,我创建了一个收藏夹表:
t.integer :chef
t.integer :recipe
t.timestamps
在routes.rb中:
get 'my_favorites', to: 'chefs#my_favorites'
resources :favorites
post 'add_recipe', to: 'recipes#add_recipe'
在RecipesController中我定义了:
def my_favorites
@favorites = current_chef.recipes
end
def add_recipe
@recipe = Recipe.find(params[:id])
current_chef.favorites.build(recipe_id: @recipe.id)
if @recipe.save
redirect_to my_favorites_path, notice: "Favorite recipe was
successfully added"
else
redirect_to my_favorites_path, flash[:error] = "There was an error
with adding recipe as favorite"
end
end
观点:
我在views / recipes / show.html.erb文件中创建了一个“添加为我最喜欢的”link_to
按钮。但是当我从浏览器中单击它时,它会返回错误:Couldn't find Recipe without an ID
。
<% if logged_in? %>
<% if current_chef.not_favorites_with?(@recipe) %>
<%= link_to "Add as my favorite", add_recipe_path(chef:
current_chef, recipe: @chef),
class: "btn btn-xs btn-success",
method: :post %>
<% else %>
<span class="label label-primary">
It's already your favorite recipe
</span>
<% end %>
<% end %>
这就是服务器中发生的事情:
Processing by RecipesController#add_recipe as HTML
Parameters: {"authenticity_token"=>"Pz5C/yK0mP5QtONHJs83fhxcrQ6Alvbp2qpPrVOiKdBKyIUys
pww/7L8S66lcOmFGWZr8Lq1ka1rt2D4FbY8NQ==", "chef"=>"9"}
Chef Load (0.3ms) SELECT "chefs".* FROM "chefs" WHERE "chefs"."id"
= ? ORDER BY "chefs"."created_at" DESC LIMIT ? [["id", 9], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find Recipe without an ID):
我不知道为什么它不能抓住食谱的id。
答案 0 :(得分:1)
在控制器中,您尝试按id
搜索配方,但在链接中传递为recipe
。
尝试将链接修改为
<%= link_to "Add as my favorite", add_recipe_path(chef:
current_chef, id: @recipe),
class: "btn btn-xs btn-success",
method: :post %>