在Rails中调用初始化变量时出错

叛徒

使用Ruby 1.9构建Rails 3.2应用程序。我正在尝试编写一个初始化3个变量的辅助方法,当我尝试从我的视图中调用初始化的变量时,出现“未定义的方法”错误。

助手文件中的方法

module StoreHelper
class Status
def initialize(product)
product_sales = product.line_items.total_product_sale.sum("quantity")
#avoid nil class errors for vol2 and 3. volume 1 can never be nil
if product.volume2.nil?
    product.volume2 = 0
end
if product.volume3.nil?
    product.volume3 = 0
end
 #Promo status logic
if (product_sales >= product.volume2) && (product_sales < product.volume3)
  @level3_status = "Active"
  @level2_status = "On!"
  @level1_status = "On!"
elsif (product_sales >= product.volume3)
   @level3_status = "On!"
   @level2_status = "On!"
   @level1_status = "On!"
else  @level3_status = "Pending"
end 
end      

然后,我尝试像这样调用初始化变量@ level3_status

 <%=level3_status (product)%>

不知道我在做什么错,任何帮助将不胜感激。

马蒂亚斯

您用ruby编程多长时间?您必须创建类的新实例才能访问外部实例。看看这些基础知识:http : //www.tutorialspoint.com/ruby/ruby_variables.htm

更新

从上面的链接。

Ruby实例变量:

实例变量以@开头。未初始化的实例变量的值为nil并使用-w选项产生警告。

这是显示实例变量用法的示例。

class Customer
  def initialize(id, name, addr)
    @cust_id=id
    @cust_name=name
    @cust_addr=addr
   end

  def display_details()
    puts "Customer id #@cust_id"
    puts "Customer name #@cust_name"
    puts "Customer address #@cust_addr"
  end
end

# Create Objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# Call Methods
cust1.display_details()
cust2.display_details()

这就是使用ruby和实例变量的方式。链接中有更多详细信息。

在您的情况下,我认为您还有另一个“错误”,您混合了一些东西。在app / helpers / store_helper.rb下?在此文件中,您应该只添加视图助手。如果我的直觉是正确的,我将按照以下方式解决您的问题:

app / helpers / store_helper.rb

module StoreHelper

  def get_level_states(product)
    product_sales = product.line_items.total_product_sale.sum("quantity")
    product.volume2 = 0 if product.volume2.nil?
    product.volume3 = 0 if product.volume3.nil?

    levels = {}
    if (product_sales >= product.volume2) && (product_sales < product.volume3)
      levels[:1] = "On!"
      levels[:2] = "On!"
      levels[:3] = "Active!"
    elsif product_sales >= product.volume3
      levels[:1] = "On!"
      levels[:2] = "On!"
      levels[:3] = "On!"
    else
      levels[:3] = "Pending"
    end

    levels
  end

end

app / views / your_views_folder / your_view.html.erb

获得不同级别的状态:

<% levels = get_level_states(product) %>

<%= levels[:1] %> # will print the level 1
<%= levels[:2] %> # will print the level 2
<%= levels[:3] %> # will print the level 3

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章