【发布时间】:2019-03-04 09:28:59
【问题描述】:
我正在循环浏览一系列产品,并在每个产品旁边显示收藏/取消收藏按钮:
<% @products.each do |product| %>
<%= product.title %>
<%= product.price %>
<%= product.description %>
<div id="favorites_grid">
<%= render partial: 'favorite_products/favorite', locals: { product: product } %>
</div>
带有收藏按钮的部分_favorite.html.erb:
<% unless current_user.favorite_products.exists?(product.id) %>
<%= link_to "Favorite", create_favorited_product_path(product_id: product.id), method: :post, :remote => true %>
<% else %>
<%= link_to "Unfavorite", favorited_product_path(product_id: product.id), method: :delete, :remote => true %>
<% end %>
表架构:
class CreateFavorites < ActiveRecord::Migration
def change
create_table :favorites do |t|
t.references :favorited, polymorphic: true, index: true
t.references :user, index: true
t.timestamps
end
end
end
模型关联:
class Favorite < ApplicationRecord
belongs_to :user
belongs_to :favorited, polymorphic: true
end
class Consumer < ApplicationRecord
has_many :favorites
has_many :favorite_products, through: :favorites, source: :favorited, source_type: 'Product'
end
控制器:
def create
@favorite = Favorite(favorited: @product, user_id: current_user.id)
respond_to do |format|
if @ favorite.save
flash.now[:success] = "You have successfully added this product to your favorites list."
format.js { render 'favorite.js.erb' }
else
flash.now[:alert] = "Something when wrong!"
format.js { render 'favorite.js.erb' }
end
end
end
def destroy
@favorite = Favorite.where(favorited_id: @product.id, user_id: current_user.id)
respond_to do |format|
@favorite.first.destroy
flash.now[:success] = "You have successfully removed this product from your favorites list."
format.js { render 'favorite.js.erb' }
end
end
我禁用了涡轮链接。
最喜欢的.js.erb:
$('#favorites_grid').html("<%= escape_javascript(render partial: 'favorite_products/favorite', locals: { product: @product } ) %>");
$("#flash").html("<%= escape_javascript(render partial: 'layouts/messages') %>");
还有路线:
post 'favorite_products', to: 'favorite_products#create', defaults: { format: 'js' }, :as => 'create_favorited_product'
delete 'favorite_products/id', to: 'favorite_products#destroy', defaults: { format: 'js' }, :as => 'favorited_product'
收藏/取消收藏按钮在第一页加载时正确呈现在每个产品旁边。该按钮也可以正常工作,它收藏/取消收藏与其关联的产品。
我遇到的唯一问题是......如果我点击任何产品以收藏或取消收藏,ajax 会将第一个按钮呈现为收藏/取消收藏。换句话说,ajax 没有根据当前状态(喜欢或不喜欢)呈现正确的按钮。如果我刷新页面,一切都会正确显示。
关于如何解决此问题的任何想法?
【问题讨论】:
标签: ruby-on-rails ajax