2013-09-21 13 views
0

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

方法帮助程序文件

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

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

回答

0

你用ruby编程多久了?您必须创建一个新的类实例才能访问外部实例。看看这些基本知识:http://www.tutorialspoint.com/ruby/ruby_variables.htm

UPDATE

从上面的链接..

Ruby的实例变量:

实例变量开始@。未初始化的实例变量的值为零,并使用-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下?在这个文件中,你应该添加视图助手。如果我和我的直觉是对的我会解决你的问题,像以下:

应用程序/佣工/ 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 

应用程序/视图/ 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 
+0

对不起,如果这是一个愚蠢的问题,我只有编程,Ruby或任何其他语言的事情,现在约3个月。不知道你的意思是通过创建一个新的类的实例,我没有看到任何关于linke的东西。你能进一步解释吗? – Renegade

+0

我更新了我的答案,让我知道如果我不正确,我的直觉你真的想要什么:) – Mattherick

+0

你的假设是现货,你的解决方案帮助。谢谢! – Renegade