【发布时间】:2015-05-16 21:31:39
【问题描述】:
我有一个问题: 我想减少 line_item 的产品数量 我使用 button_to 来减少数量(购物车将由 AJAX 更新) 顺便说一句,我无法在 line_items 的控制器中创建新操作。 我创建了新动作“less”并添加了新路线
resources :line_items do
post :less, on: :member
end
在 routes.rb 文件中。但它不起作用。 我有这个错误:
ActionController::UrlGenerationError
没有路由匹配 {:action=>"less", :controller=>"line_items", :product_id=>7} 缺少必需的键:[:id]
你能帮帮我吗?谢谢大家:)
这是我的代码。
查看:
在 line_items 控制器中:
...
def less
product = Product.find(params[:product_id])
@line_item = @cart.less_items(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to store_url}
#a respond_to passiamo il blocco con la @current_item
#si passa un blocco perchè è definito cosi il metodo
format.js { @current_item = @line_item}
format.json { render :show, status: :created, location: @line_item }
else
format.html { render :new }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
...
购物车模型:
def less_items(product_id)
current_item = line_items.find_by(product_id: product_id)
if current_item && current_item > 1
current_item.quantity -= 1
else
#don't do nothing
end
current_item
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 routes