我正在構建一個應用程序,其中user(seller)
可以創建項目,然後另一個user(viewer)
可以查看這些項目,如果他願意,可以查看add to favorites
。Rails 5:實現'添加到收藏夾'
這是我已經得到了迄今:
create_table "items", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "image"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "category_id"
t.json "attachments"
end
create_table "favorites", force: :cascade do |t|
t.bigint "viewer_id"
t.string "favorited_type"
t.bigint "favorited_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["favorited_type", "favorited_id"], name: "index_favorites_on_favorited_type_and_favorited_id"
t.index ["viewer_id"], name: "index_favorites_on_viewer_id"
end
viewer.rb
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
favorite.rb
class Favorite < ApplicationRecord
belongs_to :viewer
belongs_to :favorited, polymorphic: true
end
favorite_items_controller.rb
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
end
我將此添加到views/items/show.html.erb以添加或刪除收藏夾。
<%- unless current_viewer.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 -%>
,併到這裏一切正常,當我點擊add to favorites
...的鏈接更改爲remove from favorites
...當我點擊remove from favorites
鏈接變回add to favorites
。
所以,現在,我想實現以下但不知道如何:我 要環通的最愛,並顯示在index.html.erb
所有喜愛的項目與每個項目的詳細信息(名稱,價格)一起。