[英]link_to issue with calling another method ruby on rails
I have a products database i'm accessing and outputting some info on /products/show 我有一个产品数据库,我正在访问和输出有关/ products / show的信息
I'm trying to add a link_to in the loop to go to the action add_to_cart so I can simulate an add to cart feature. 我正在尝试在循环中添加一个link_to以转到操作add_to_cart,以便可以模拟“添加到购物车”功能。 Right now I'm just trying to get the id of the corresponding record when the link is clicked and then I want to do another loop in the shopping cart section to output that record in a table row.
现在,我只是想在单击链接时尝试获取相应记录的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 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 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
The error I'm getting: 我得到的错误:
undefined local variable or method `add_to_cart' for #<#<Class:0x40c31b8>:0x3988f08>
I'm still learning so it's not entirely clear to me 我还在学习,所以对我来说还不是很清楚
here is what the command put out: 这是命令输出的内容:
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
Change this line: 更改此行:
<%= link_to("Add to Cart", {:action => add_to_cart, :id => product.id}, :class => 'button radius') %>
To this: 对此:
<%= link_to("Add to Cart", {:action => 'add_to_cart', :id => product.id}, :class => 'button radius') %>
You had forgotten to enclose the name of the action within quotes and so it was being interpreted as a local variable or method. 您忘记了将动作的名称括在引号中,因此将其解释为局部变量或方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.