【问题标题】:Undefined method 'paypal_url' from a partial部分未定义的方法“paypal_url”
【发布时间】:2014-04-09 07:41:44
【问题描述】:

大家晚上好,

我一直在尝试解决这个问题,我很确定这是我所缺少的非常简单的东西......

我目前有一个网上商店,它允许客户将产品添加到购物车,然后允许客户通过 PayPal 付款。

如果我尝试从购物车中的“E.G”付款没有问题

http://localhost:3000/carts/1

但是,我创建了一个显示所有购物车项目的部分(此部分显示在导航栏的下拉列表中),并且客户应该能够从该下拉列表中单击“结帐”。目的是它的工作方式与进入购物车的方式相同;它应该把他们直接带到贝宝支付。这部分在下面。

_display_cart.htlm.erb

<% current_cart.line_items.each do |item| %>
 <li> <%= item.product.title %>  
 <%=  number_to_currency item.product.price , :unit =>"&pound" %> &times; <%= item.quantity %> </li>
<% end %>

<div align="right">
 <%= number_to_currency(current_cart.grand_total,  :unit => "&pound;") %>&nbsp;
</div>
 </ul>
<%= link_to "Checkout", @cart.paypal_url(products_url) %>

如果我从产品展示页面将商品添加到购物车,同时以下内容已到位:

<%= link_to "Checkout", @cart.paypal_url(products_url) %> 

我得到一个未定义的方法错误:

undefined method `paypal_url' for nil:NilClass

然而paypal_url是在cart.rb中定义的,如下。

    def paypal_url(return_url)
values = {
:business => 'EMAIL',
:upload => 1,
:return => return_url,
:invoice => id
}
line_items.each_with_index do |item, index|
values.merge!({
  "amount_#{index+1}" => item.product.price,
  "item_name_#{index+1}" => item.product.title,
  "item_number_#{index+1}" => item.id,
  "quantity_#{index+1}" => item.quantity
})
end
"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
end

有趣的是,如果我进入 localhost:3000/carts/1,我的导航栏中的下拉菜单可以完美运行,并且该错误不再阻止我访问该站点。然后导航栏下拉菜单中的结帐按钮将我带到PayPal;它只是不在网站的其余部分这样做,仅在购物车视图中(仅显示,而不是索引)。

如果它会像我想象的那么简单,请原谅我,我已经有几个月没有玩铁轨了,而且我一开始就不是那么好!

【问题讨论】:

    标签: ruby-on-rails paypal ruby-on-rails-3.2 partials


    【解决方案1】:

    您收到错误是因为未设置 @cart。目前,它的值在部分_display_cart.html.erb 内为零。请确保在渲染此部分之前设置 @cart 的值。

    例如:

    在呈现完整页面(在其中呈现部分页面)的操作中设置 @cart 的值。

    在渲染部分时将@cart 传递给locals

    <%= render :partial => 'display_cart', :locals => {:cart => @cart} %>
    

    并在部分访问中将其作为cart 而不是@cart

    更新

    OP 想检查他在current_cart 中已有的当前购物车内容。

    更新链接

    <%= link_to "Checkout", @cart.paypal_url(products_url) %>
    

    <%= link_to "Checkout", current_cart.paypal_url(products_url) %>
    

    【讨论】:

    • 您好,谢谢您的回复,但我不知道该怎么做,大脑今天处于“derp”模式。另外,我在stackoverflow.com/questions/1850905/… 上关注了所有内容,认为这会有所帮助,但无济于事。再次感谢本。
    • 再次您好,感谢您的快速回复。我之前尝试过类似的东西(尽管我不知道将 @ 放在部分内部)。但是,这仍然会导致“nil:NilClass 的未定义方法 `paypal_url'”,所以我不知道问题出在哪里!
    • 是的,我已经这样做了,我的意思是我之前读过的帖子没有说明,但是我已经按照你说的做了,但是没有用。抱歉,如果我不清楚。 _navigation.html.erb 现在说:&lt;%= render :partial =&gt; '/display_cart', :locals =&gt; {:cart =&gt; @cart} %&gt; 和 _display_cart.html.erb 说&lt;%= link_to "Checkout", cart.paypal_url(products_url) %&gt;
    • 你在哪里设置@cart 变量?共享呈现主页的控制器代码(在其中呈现部分 _display_cart.html.erb)。
    猜你喜欢
    • 2014-06-28
    • 2014-03-08
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多