几个小时前,我在store_controller.rb上开发了一种模糊方法。这个名为fuzzy的方法获取产品数量作为参数,然后使用if语句检查该值并返回一个名为disp的对象。我在视图index.html.erb上调用此方法。
现在,在视图中,我插入了一行代码来检查disp的值。根据disp的值,视图必须打印出不同的图像,以显示产品的可用数量,例如available或not available。但是,插入这一行时,我得到了一个错误:undefined local variable or method 'disp' for #<ActionView::Base:0x6dc1864>
这是视图index.html.erb的代码
<% for product in @products -%>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%=h product.title %></h3>
<%= product.descr %>
<br /><div class="disp">
<p><% fuzzy(product.quantity) %><% if disp == 0 %><%= image_tag("nodisp.png", :border => "0") %><% end %><% if disp == 1 %><%= image_tag("disp.png", :border => "0") %><% end %></p>
</div><br />
<p><span class="price"><%= number_to_currency(product.price, :unit => "€") %></span></p>
<% form_remote_tag :url => { :action => :add_to_cart, :id => product } do %>
<%= submit_tag "add to cart!" %>
<% end %>
</div>
<% end %>请注意fuzzy方法的调用。此方法插入到store_controller.rb中
def fuzzy(q)
disp = (q-5)/20
if q > 9 then disp = 1 end
if q < 7 then disp = 0 end
return disp
end问题是:当我在视图中执行代码,调用模糊方法时,我如何获得方法的结果disp,并使用if语句在视图上显示它?有可能吗?
发布于 2011-04-19 01:07:53
我将解决您所遇到的问题和解决方案。
问题是,您希望在视图中访问变量disp,但是在函数fuzzy执行完毕后,此变量超出了范围。如果这没有意义,我会读到scope in programming。
解决方案是您的方法返回一个值(在Ruby语言中,您实际上不需要显式地声明return,因为返回了最后执行的行),所以现在您需要使用从fuzzy调用返回的值来赋给一个变量。
解决方案(为了让您的代码正常工作)是将变量设置为返回值,如下所示:
<% disp = fuzzy(product.quantity) %>请记住,此disp与您在function fuzzy中创建的不同。它们在两个不同的作用域中。
发布于 2011-04-19 00:56:43
由于已经从fuzzy方法返回了所需的值,因此可以将<% fuzzy(product.quantity) %>替换为<% disp = fuzzy(product.quantity) %>,以将名为disp的变量设置为fuzzy方法的返回值。这应该适用于您的其余代码。
https://stackoverflow.com/questions/5706198
复制相似问题