link_to问题在rails上调用另一个方法ruby

时间:2014-01-08 01:34:47

标签: mysql ruby-on-rails

我有一个产品数据库,我正在访问并输出/ products / show

上的一些信息

我正在尝试在循环中添加link_to以转到操作add_to_cart,以便我可以模拟添加到购物车功能。现在我只是想点击链接时获取相应记录的id,然后我想在购物车部分再做一个循环,将该记录输出到表格行中。

products_controller

class ProductsController < ApplicationController

  def index
    show
    render 'show'
  end

  def show
    @products = Product.order("products.name ASC")
  end

  def add_to_cart
    @product = Product.find(params[:id])
  end

end

show.html.erb

<div class="row">
<div id="shoppingCart">
  <h1>Shopping Cart</h1>
    <table border="0" cellpadding="0" cellspacing="0" id="cartContainer" width="100%">
      <tr>
        <th>Image</th>
        <th>Name</th>
        <th>Description</th>
        <th>Price</th>
        <th>Quantity</th>
      </tr>
    </table>
</div>
</div>

<div class="large-12 columns">
  <div class="row">
    <% @products.each do |product| %>
        <div class="large-3 columns panel radius prodContainer" style="height: 600px">    <h2 class="prodTitle"><%= product.name %></h2><br><h3 class="prodUnitPrice">$<%= product.unit_price %></h3><br>ID: <%= product.id %><br><br>
    <p class="prodDesc"><%= product.description %></p>
    <!-- Add to Cart Link -->
    <%= link_to("Add to Cart", {:action => add_to_cart, :id => product.id}, :class => 'button radius') %>
    </div>
  <% end %>
</div>

的routes.rb

Catalog::Application.routes.draw do
  resources :home do
    get 'home/index'
  end

  resources :products do
    get 'products/show'
    get 'products/add_to_cart'
  end

  root :to => 'home#index'

  get ':controller(/:action(/:id(.:format)))'
end

我收到的错误:

undefined local variable or method `add_to_cart' for #<#<Class:0x40c31b8>:0x3988f08>

我还在学习,所以对我来说并不完全清楚

这是命令发布的内容:

c:\Sites\Catalog>bundle exec rake routes | grep add_to_cart
product_products_add_to_cart GET    /products/:product_id/products/add_to_cart(.
:format) products#add_to_cart

1 个答案:

答案 0 :(得分:0)

更改此行:

<%= link_to("Add to Cart", {:action => add_to_cart, :id => product.id}, :class => 'button radius') %>

对此:

<%= link_to("Add to Cart", {:action => 'add_to_cart', :id => product.id}, :class => 'button radius') %>

您忘记将动作的名称括在引号内,因此它被解释为局部变量或方法。