创建新路线 Rails 4
Create new route Rails 4
我有一个问题:
我想减少 line_item 产品的数量
我使用 button_to 来减少数量(购物车将由 AJAX 更新)
顺便说一句,我无法在 line_item 的控制器中创建新操作。
我创建了新操作 "less" 并添加了新路线
resources :line_items do
post :less, on: :member
end
在 routes.rb 文件中。但它不起作用。
我有这个错误:
ActionController::UrlGenerationError
没有路由匹配 {:action=>"less", :controller=>"line_items", :product_id=>7} 缺少必需的键:[:id]
你能帮帮我吗?谢谢大家:)
这是我的代码。
查看:
<%= button_to '-', less_line_item_path(product_id: line_item.product_id), remote: true %>
在 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
问题是您没有 :id
字段。
将 button_to 更改为...
<%= button_to '-', less_line_item_path(line_item, product_id: line_item.product_id), remote: true %>
这将在 :id
参数中传递 line_item id,路由会很开心。
我有一个问题: 我想减少 line_item 产品的数量 我使用 button_to 来减少数量(购物车将由 AJAX 更新) 顺便说一句,我无法在 line_item 的控制器中创建新操作。 我创建了新操作 "less" 并添加了新路线
resources :line_items do
post :less, on: :member
end
在 routes.rb 文件中。但它不起作用。 我有这个错误:
ActionController::UrlGenerationError
没有路由匹配 {:action=>"less", :controller=>"line_items", :product_id=>7} 缺少必需的键:[:id]
你能帮帮我吗?谢谢大家:)
这是我的代码。
查看:
<%= button_to '-', less_line_item_path(product_id: line_item.product_id), remote: true %>
在 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
问题是您没有 :id
字段。
将 button_to 更改为...
<%= button_to '-', less_line_item_path(line_item, product_id: line_item.product_id), remote: true %>
这将在 :id
参数中传递 line_item id,路由会很开心。