代码之家  ›  专栏  ›  技术社区  ›  dgreen22

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

  •  0
  • dgreen22  · 技术社区  · 6 年前

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

    我正在努力 .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
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   iGian    6 年前

    尝试类似的操作,检查产品是否已在购物车中。

    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
    

    然后使用 @product_already_in_the_cart 对于视图中的if语句。

    unless @product_already_in_the_cart
    
        2
  •  2
  •   bo-oz    6 年前

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

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