【问题标题】:Adding attributes into a cart将属性添加到购物车
【发布时间】:2014-07-11 06:30:23
【问题描述】:

现在在下面的产品视图中,我有 2 个属性我想通过 photo.id 传递 type.id 和 size.id

它们都将保存在同一个订单项中

button_to 是一个远程操作,因此在按下按钮后它不会离开页面。

在 line_items 控制器中添加要传递给 create 的属性的最佳方法是什么?

产品视图

    %b Paper Type

    = select(:type_id, :type, options_from_collection_for_select_with_attributes(Type.all, 'id', 'name', 'data-price', 'price'), { :include_blank=>false }, {:class => 'vars'})

  %p
    %b Paper Size

    = select(:type_id, :type, options_from_collection_for_select_with_attributes(Size.all, 'id', 'name', 'data-price', 'price'), { :include_blank=>false }, {:class => 'vars'})

  %p
    %b Total:
    %span#total
      %input{:type=>"hidden", value: @photo.price, name: 'price', id: 'baseprice'}

      = number_to_currency (@photo.price)

    %br
    = button_to 'Add to Cart', line_items_path(photo_id: @photo.id), remote: true
    %br

订单项控制器

def create
photo = Photo.find(params[:photo_id])
@line_item = @cart.add_product(photo.id)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to @line_item.cart }
    format.js { @current_item = @line_item }
    format.json { render action: 'show', status: :created, location: @line_item }
  else
    format.html { render action: 'new' }
    format.json { render json: @line_item.errors, status: :unprocessable_entity }
  end
 end
end

cart.rb 模型

def add_product(photo_id)
  current_item = line_items.find_by(photo_id: photo_id) 
  if current_item
      current_item.quantity = current_item.quantity.to_i + 1
  else
      current_item = line_items.build(photo_id: photo_id, quantity: 1)
  end
    current_item
end

购物车初始化关注点/current_cart.rb

def set_cart 
  @cart = Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    @cart = Cart.create
    session[:cart_id] = @cart.id
end

编辑:添加购物车初始化程序和 add_product 方法

【问题讨论】:

  • 这一行中的add_product是什么@line_item = @cart.add_product(photo.id)@cart在哪里初始化?
  • 我有一个控制器来初始化购物车,而 add_product 是购物车模型中的一种方法,用于添加 line_itens 和数量。我会更新最初的帖子

标签: ruby-on-rails charts


【解决方案1】:

button_to

button_to 似乎能够将参数传递给方法,然后将其呈现为hidden fields

这意味着您应该能够在 button_to 方法中将额外属性作为参数传递 - 允许您在控制器后端处理它们:

<%= button_to line_items_path(photo_id: @photo.id, type_id: "X", size_id: "Y") %>

--

表格

问题是你只能传递static 的参数。我看到您可以选择它们,这完全适合拥有form(特别是form_tag):

<%= form_tag line_items_path(photo_id: @photo.id) do %>
   <%= select_tag :type_id .....%>
   <%= select_tag :size_id .....%>
   <%= submit_tag "Save" %>
<% end %>

将允许您在button_to helper 的范围之上将您需要的参数发送到您的应用程序,从而允许您在后端执行以下操作:

params[:type_id]
params[:size_id] 

etc

【讨论】:

  • 在 的情况下,我必须捕获 2当我选择值时选择并传递给 button_to ......现在,我该怎么做?
  • 必须使用静态值来完成 - 这就是为什么我也详细介绍了 form_tag 方式:)
  • 我会尝试使用重定向返回或重定向到购物车,看看会发生什么
猜你喜欢
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多