无法创建可以在rails中发送POST请求的锚点

时间:2012-08-29 20:23:28

标签: html ruby-on-rails ruby

我正在从一本名为Agile Web Development的书中进行练习。任务是:

用户可以在踢项目图片时将产品添加到购物车。 所以我将图像标记包装成锚标记。就像<%= link_to image_tag(product.image_url), line_items_path(:product_id => product), html_options = {:method => :post} %> 一样 我踢图像似乎很好,但它不会在购物车中添加任何东西。 我查看了discussion in book's website,其中一些解决方案与我的解决方案类似。但它们也不起作用。

当我踢图像时代码将会运行:

# POST /line_items
# POST /line_items.json
def create
  # for exercise only
  session[:couter] = nil

  @cart = current_cart
  product = Product.find(params[:product_id])
  @line_item = @cart.line_items.build(:product=>product)

  respond_to do |format|
    if @line_item.save
      format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
      format.json { render json: @line_item, status: :created, location: @line_item }
    else
      format.html { render action: "new" }
      format.json { render json: @line_item.errors, status: :unprocessable_entity }
    end
  end
end

3 个答案:

答案 0 :(得分:1)

我认为您需要button_to,而不是link_to。您无法从锚链接发送POST请求。

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to

答案 1 :(得分:1)

你快到了。你想要这样的东西:

<%= link_to image_tag(product.image_url), line_items_path(:product_id => product), :method => :post %>

答案 2 :(得分:0)

我弄清楚发生了什么。 这是本书的问题,而不是轨道。

原始<%= javascript_tag 'application %>'

这本书告诉我把它改成<%= javascript_include_tag :default %>

所以我无法导入javascript库:(

相关问题