【发布时间】: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