code4j
code4j

Reputation: 4666

Cannot create anchor which can send POST request in rails

I am doing an exercise from a book called Agile Web Development. The mission is that:

The users can add product to the cart when they kick the item image. So I wrap the image tag into an anchor tag. Just like <%= link_to image_tag(product.image_url), line_items_path(:product_id => product), html_options = {:method => :post} %> It seems to be fine which I kick the image, but it does not add anything into the cart. I checked out the discussion in book's website, some of the solutions are similar to my one. But they also don't works.

Code is going to run when I kick the image:

# 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

Upvotes: 0

Views: 913

Answers (3)

code4j
code4j

Reputation: 4666

I figured out what is going on. It is the problem of the book, not the rails.

The original <%= javascript_tag 'application %>'

The book taught me change it to<%= javascript_include_tag :default %>

So I cannot import the javascript Library :(

Upvotes: 0

Edd Morgan
Edd Morgan

Reputation: 2923

You're almost there. You want something like this:

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

Upvotes: 1

JGrubb
JGrubb

Reputation: 889

I think you want button_to, not link_to. You can't send a POST request from an anchor link.

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

Upvotes: 1

Related Questions