我想实现添加到收藏夹,我收到此错误:Rails的:无法与“ID”找项目=
ActiveRecord::RecordNotFound in FavoriteItemsController#index
Couldn't find Item with 'id'=
这是在错误弹出,在以下链接:
<%= link_to "Favorite Items", favorites_path, method: :get, :class => 'navbar-link' %>
模型关联
class Favorite < ApplicationRecord
belongs_to :viewer
belongs_to :favorited, polymorphic: true
end
class Viewer < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :favorites
has_many :favorite_items, through: :favorites, source: :favorited, source_type: 'Item'
end
路线:
get '/favorites', to: 'favorite_items#index', as: 'favorites'
resources :favorite_items, only: [:create, :destroy]
和我的节目页面上的add
或remove
收藏夹链接:
<%- unless current_shopper.favorite_items.exists?(id: @item.id) -%>
<%= link_to 'Add to favorites', favorite_items_path(item_id: @item), method: :post %>
<%- else -%>
<%= link_to 'Remove from favorites', favorite_item_path(@item), method: :delete %>
<%- end -%>
控制器
class FavoriteItemsController < ApplicationController
before_action :set_item
def index
@favorites = current_viewer.favorites
end
def create
if Favorite.create(favorited: @item, viewer: current_viewer)
redirect_to @item, notice: 'Item has been favorited'
else
redirect_to @item, alert: 'Something went wrong...*sad panda*'
end
end
def destroy
Favorite.where(favorited_id: @item.id, viewer_id: current_viewer.id).first.destroy
redirect_to @item, notice: 'Item is no longer in favorites'
end
private
def set_item
@item = Item.find(params[:item_id] || params[:id])
end
和指数环通的青睐的项目,虽然不知道这是正确的因为错误在循环之前停止:
<% @favorites.each do |item| %>
<tr>
<td><%= item.title %></td>
<td><%= item.price %></td>
<td><%= link_to 'Remove from favorites', favorite_items_path(@item.id), method: :delete %></td>
< /tr>
<% end %>
更新1
这是当我点击添加到收藏夹
Item Exists (4.3ms) SELECT 1 AS one FROM "items" INNER JOIN "favorites"
ON "items"."id" = "favorites"."favorited_id" WHERE "favorites"."viewer_id"
= $1 AND "favorites"."favorited_type" = $2 AND "items"."id" = $3 LIMIT $4
[["viewer_id", 2], ["favorited_type", "Item"], ["id", 4], ["LIMIT", 1]]
items_controller.rb
def create
@item = Item.new(item_params)
respond_to do |format|
if @item.save
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: @item }
else
format.html { render :new }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
def show
@comments = Comment.where(item_id: @item).order("created_at DESC")
@items = Item.find(params[:id])
end
你能否证实@item不是零? – krishnar
在我的演出页面上添加或删除收藏夹链接:您的演出活动在哪里? – krishnar
@krishnar ...显示动作在'items_controller.rb'中,并且在它里面@ @ items = Item.find(params [:id])' – Theopap