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に追加しました。私はadd to favorites
をクリックしたとき
<%- 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 -%>
とアップ
はremove from favorites
に...、すべてが正常に動作し、リンクの変更をここで...と私は
remove from favorites
をクリックするとリンクが戻っ
add to favorites
に変更します。
ここで、私は以下を実装したいと思います。どうすればいいですか? お気に入りのアイテムをループして、すべてのアイテムの詳細(タイトル、価格)とともにお気に入りのアイテムをindex.html.erb
に表示します。