Rails 5:实现'添加到收藏夹'

时间:2017-10-09 08:57:05

标签: ruby-on-rails ruby ruby-on-rails-4

我正在构建一个应用,其中user(seller)可以创建项目,然后另一个user(viewer)可以查看项目,add to favorites是否可以。

这是我迄今为止所得到的:

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上显示所有喜爱的项目以及每个项目的详细信息(标题,价格)。

1 个答案:

答案 0 :(得分: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

希望它能给你基本的想法。