首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查对象是否出现故障- Rails 5

检查对象是否出现故障- Rails 5
EN

Stack Overflow用户
提问于 2018-07-31 17:30:35
回答 2查看 27关注 0票数 0

我正在尝试设置一个“添加到购物车”按钮,在用户将产品添加到购物车后,该按钮将变为禁用状态,除非该产品从购物车中移除。

我正在尝试.present?,但它似乎忽略了这一点,无论产品是否已经在购物车中。即使我的购物车是完全空的,它仍然显示禁用按钮。

有什么线索我该怎么解决这个问题吗?

查看(产品展示):

代码语言:javascript
复制
 <% 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 %>

产品控制器:

代码语言:javascript
复制
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

模型

代码语言:javascript
复制
class Order < ApplicationRecord
  has_many :line_items
  belongs_to :user, optional: true


end

行项目模型

代码语言:javascript
复制
class LineItem < ApplicationRecord
  belongs_to :order, optional: true
  belongs_to :product, optional: true
  belongs_to :service, optional: true
end

服务模型

代码语言:javascript
复制
class Service < ApplicationRecord
    has_many :line_items
end

产品型号

代码语言:javascript
复制
class Product < ApplicationRecord
    has_many :line_items
end
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-31 18:06:07

尝试像这样检查产品是否已经在购物车中。

代码语言:javascript
复制
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

代码语言:javascript
复制
unless @product_already_in_the_cart
票数 1
EN

Stack Overflow用户

发布于 2018-07-31 17:50:29

问题是您是从产品端查看LineItem的。因此,这意味着如果产品有任何LineItem,它将禁用该按钮。因此,如果用户A已经订购了产品,则该按钮将对所有人隐藏!

您需要更改条件:

代码语言:javascript
复制
 <% 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 %>

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51610064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档