【问题标题】:Rails. Association of the same line items in the cart导轨。购物车中相同订单项的关联
【发布时间】:2016-11-25 08:26:44
【问题描述】:

当它们添加到购物车时,我需要关联相同的订单项。现在我在每个提交表单后都有新的订单项。我尝试在订单项控制器中使用 add_product 修复它:

订单项控制器:

def create
  @cart = current_cart
  @line_item = @cart.add_product(@product.id)    
end

购物车模型

has_many   :line_items, dependent: :destroy 

def add_product(product_id)
    current_item = line_items.find_by(product_id: product_id)
    if current_item
        current_item.quantity += line_item.quantity.to_i
    else
        current_item = line_items.build(product_id: product_id)
    end
    current_item
end

显示产品页面中的订单项表单部分呈现:

= form_for (@line_item) , remote: true do |f| 
    div class="input-group"
        = f.number_field :quantity, value: 1, class: "form-control", min: 1 
        div class="input-group-btn"
                = f.hidden_field :product_id, value: @product.id 
                = f.submit "Add to Cart"

但提交表单后出现错误:“NoMethodError (undefined method `id' for nil:NilClass):”

如何将@product.id 从表单传输到控制器?

UPD 在 line_item 控制器中添加@product

def create
  @product = Product.find(params[:line_item][:product_id])
  @cart = current_cart
  @line_item = @cart.add_product(@product.id)    
end

【问题讨论】:

  • 我认为你可以看到这个错误,因为表单本身没有得到@product
  • 不,@product 的形式没问题。
  • 好的,试试@product = Product.find_by_id(params[:line_item][:product_id])
  • 什么都没有。没有错误,购物车中没有 line_item。
  • 您可以在每一步使用 puts "...#{@product.id}" 打印产品 ID,这样您就可以测试丢失它的位置

标签: ruby-on-rails


【解决方案1】:

您必须通过参数中的 product_id 在控制器的创建操作(或 before_action)中找到@product。 比如:

@product = Product.find(params[:line_item][:product_id])

(虽然不是很漂亮)

【讨论】:

  • 在 line_item 控制器的创建操作中添加 @product = Product.find(params[:line_item][:product_id])。错误丢失,但 line_item 未添加到购物车中。
  • 此代码 current_item = line_items.build(product_id: product_id) 不会在数据库中保存记录,您应该使用 create 而不是 build 来执行此操作
  • 新问题 = 新问题。感谢您的帮助!
猜你喜欢
  • 2012-09-26
  • 2018-03-01
  • 2011-08-03
  • 2013-12-13
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
相关资源
最近更新 更多