mysql - ruby on Rails 调用另一个方法的 link_to 问题

标签 mysql ruby-on-rails

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

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

产品 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

最佳答案

更改此行:

<%= 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') %>

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

关于mysql - ruby on Rails 调用另一个方法的 link_to 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20985430/

相关文章:

mysql - 在 MySQL 中使用 LIKE 运算符和逗号问题

ruby-on-rails - 滚动条对 rails 性能的影响

ruby-on-rails - rake 数据库 :migrate error - paperclip

php - Laravel 忽略我的 PHP 设置并超时

php - 将 3 个 MYSQL 查询优化为一个

ruby-on-rails - rails 3.1 中的 radio_button_tag

ruby-on-rails - 无法将本地主机连接到 heroku 数据库

ruby-on-rails - 如何在ActiveAdmin中自定义默认登录页面?

mysql - 如何在 MySQL 中重新排列表?

php - jQuery 验证远程方法使用来检查用户名是否已存在