新手问题 点击图片添加物品到购物车的疑问

torubylist · 2015年10月27日 · 最后由 torubylist 回复于 2015年10月27日 · 1504 次阅读

route

resources :line_items
  resources :carts
   resources :sites
  root :to => 'store#index', :as => 'store'
   resources :products

###line_items_controller.rb

def create
  @cart      = current_cart
  product    = Product.find(params[:product_id])
  @line_item = @cart.add_product(product.id)

  respond_to do |format|
    if @line_item.save
      format.html { redirect_to(@line_item.cart) }
      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

###store.index.erb

<h1>Your Pragmatic Catalog</h1>
<% @products.each do |product| %>
  <div class="entry">
    <%= link_to image_tag(product.image_url),line_items_path(:product_id => product),
                                            method: :post %><br />
    <h3><%= product.title %></h3>
    <%= sanitize(product.description) %>
    <div class="price_line">
      <span class="price"><%= number_to_currency(product.price) %></span>
      <%= button_to 'Add to Cat',line_items_path(:product_id => product )%>
    </div>
  </div>
<% end %>

点击图片之后。却并没有实现添加到购物车这个功能。而且 redirect 的页面也不对。请问哪里有问题啊?

<%= button_to 'Add to Cat',line_items_path(:product_id => product )%>

这里 line_items_path 从路由上面来看,应该是 POST 动作才可以的!你可以尝试这样

<%= button_to 'Add to Cat',line_items_path(:product_id => product), method: 'post' %>

#1 楼 @huacnlee 谢谢。不是这句有问题。button_to 默认就是 post 方法。是这个图片 <%= link_to image_tag(product.image_url),line_items_path(:product_id => product),method: :post %>
。我想通过点击图片实现添加功能。

#2 楼 @torubylist 修改 link_to 问题解决了吧?

#3 楼 @huacnlee 如何修改 link_to?

#4 楼 @torubylist 你 button_to 那个按钮能达到你期望的效果吗? 如果可以,你可以让点击图片按钮那个动作,用 JS 调用 button_to 那个按钮的点击,这样就实现了。

#5 楼 @huacnlee button_to 可以实现。JS 基本不会。我去看看文档。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号