【问题标题】:Create new route Rails 4创建新路线 Rails 4
【发布时间】: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


    【解决方案1】:

    问题是你没有:id 字段。

    将 button_to 更改为...

    <%= button_to '-', less_line_item_path(line_item, product_id: line_item.product_id), remote: true %>
    

    这将通过:id 参数中的line_item id,并且路由会很开心。

    【讨论】:

    • 当你有一个“成员”路由时,它适用于类的特定实例,因此它期望具有特定对象的 id。您可以使用less_line_item_path(line_item.id, product_id: line_item.product_id) 来传递 id,但如果您传递对象本身,则会自动提取 id。如果您已将其设为“集合”路由,则无需指定对象即可获取对象 ID,因为无需特定 ID 即可。
    • 嗯,我明白,但如果我输入 :collection 我有这个错误:未定义的方法 `less_line_item_path' for #:0x546a950>
    • 因为如果它是:collection(可能有很多line_items)你需要使用复数...less_line_items_path
    • 是的,现在错误消失了,但我的功能不起作用。你能看看有什么问题吗?非常感谢
    • 在控制台中我看到:NoMethodError undefined method less_items
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多