【发布时间】:2015-05-17 06:57:51
【问题描述】:
我有这个问题: 我应该减少 line_item 的属性“数量”。 所以我创建了一个 button_to 来做到这一点。 问题是,即使我在 line_item 的控制器中创建了新操作“less”并将其添加到 routes 中,我的功能也不起作用。 你能告诉我是什么问题吗?
Routes.rb
resources :line_items do
post :less, on: :collection
end
Line_item 控制器 在这个文件中,我包含了 set_cart 方法(它有效),所以我可以使用@cart vaiable 我写了 before_action :set_cart, only: [:create,:less]
def less
puts "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"
#Rails sa di dover prendere l' ID da product per eseguire il find :D
product = Product.find(params[:product_id])
#aggiungiamo un prodotto in piu'
#ritorna un current_item
@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
结束
购物车型号:
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
current_item = line_items.build(product_id: product_id)
end
current_item
end
控制台对我说:
新问题:
感谢 Tomáš Dundáček,我知道我必须编辑 cancan 能力文件以允许更少的方法通过。现在我仍然有问题。图片如下:
【问题讨论】:
-
你好像是从某个
before_action重定向过来的,这可能吗?
标签: ruby-on-rails ruby-on-rails-4 routes action