2017-10-09 119 views
0

我正在構建一個應用程序,其中user(seller)可以創建項目,然後另一個user(viewer)可以查看這些項目,如果他願意,可以查看add to favoritesRails 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所有喜愛的項目與每個項目的詳細信息(名稱,價格)一起。

回答

0

我希望它是要篩選FavouriteItems從項目,所以你需要一個表來存儲FavouriteItems中,你需要ITEM_ID誰選擇項目簡單的邏輯,viewer_id(用戶存儲在他的favourite_items)就是這樣。

class Viewer < ApplicationRecord 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 


# has_many :favorites # I don't know why it is all here 
# has_many :favorite_items, through: :favorites, source: :favorited, source_type: 'Item' 
    has_many :favorite_items 
    end 

然後,你需要這樣做是爲了您的FavouriteItem類

class FavoriteItem < ApplicationRecord 
belongs_to :viewer 
end 

希望它會給你想要的東西的基本理念。