检查是否存在物体故障-轨道5



我正在尝试设置一个"添加到购物车"按钮,在用户将产品添加到购物篮后,除非将产品从购物车中删除,否则该按钮将被禁用。

我正在尝试.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

问题是您正在从产品端查看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 %>

总的来说,我确实觉得这对一种观点来说有点逻辑,但这可能是一个不同的讨论。

尝试这样的操作来检查产品是否已经在购物车中。

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

最新更新