我正在尝试设置一个“添加到购物车”按钮,在用户将产品添加到购物车后,该按钮将变为禁用状态,除非该产品从购物车中移除。
我正在尝试.present?,但它似乎忽略了这一点,无论产品是否已经在购物车中。即使我的购物车是完全空的,它仍然显示禁用按钮。
有什么线索我该怎么解决这个问题吗?
查看(产品展示):
<% if @product.price.present? %>
<% if !@product.line_items.present? %>
<%= form_for @line_item do |f| %>
<%= f.hidden_field :product_id, value: @product.id %>
<%= f.submit "Add to cart" %>
<% end %>
<% else %>
<%= button_to "Added to cart", "", class: "", disabled: true %>
<% end %>
<% end %>产品控制器:
class ProductController < InheritedResources::Base
before_action :set_product, only: [:show]
def show
@line_item = current_order.line_items.new
end
def set_product
@product = Product.find_by(product_number: params[:product_number])
end
end模型
class Order < ApplicationRecord
has_many :line_items
belongs_to :user, optional: true
end行项目模型
class LineItem < ApplicationRecord
belongs_to :order, optional: true
belongs_to :product, optional: true
belongs_to :service, optional: true
end服务模型
class Service < ApplicationRecord
has_many :line_items
end产品型号
class Product < ApplicationRecord
has_many :line_items
end发布于 2018-07-31 18:06:07
尝试像这样检查产品是否已经在购物车中。
def show
@line_item = current_order.line_items.new
@product_already_in_the_cart = current_order.line_items.pluck(:product_id).include? @product.id
end然后对视图中的if语句使用@product_already_in_the_cart。
unless @product_already_in_the_cart发布于 2018-07-31 17:50:29
问题是您是从产品端查看LineItem的。因此,这意味着如果产品有任何LineItem,它将禁用该按钮。因此,如果用户A已经订购了产品,则该按钮将对所有人隐藏!
您需要更改条件:
<% if @product.price.present? %>
<% if @line_item.where(product: @product).empty? %>
<%= form_for @line_item do |f| %>
<%= f.hidden_field :product_id, value: @product.id %>
<%= f.submit "Add to cart" %>
<% end %>
<% else %>
<%= button_to "Added to cart", "", class: "", disabled: true %>
<% end %>
<% end %>总的来说,我确实觉得这对于一个视图来说有点太多的逻辑,但这可能是一个不同的讨论。
https://stackoverflow.com/questions/51610064
复制相似问题