1

我在我的lib文件夹模块中有一个API调用,它返回我需要在我的视图中使用的变量。 例如:我定义我的模块中从lib模块传递实例变量到控制器

module ProdInfo 
    def get_item_info(id) 
    @url = "Blah" 
    end 
end 

我控制器以下:

class RecommendationsController < ApplicationController 
    require 'get_prod_info' 
    include ProdInfo 

    def index 
    @product = Product.find(params["product_id"]) 
    get_item_info(@product.id) 
    end 
end 

我想在我的建议,呼吁@url查看,但其没有被正确调用。如果我将@url放入模块中,它会打印出正确的URL,但如果我在控制器中执行相同操作,则不会输出任何内容。

+0

我想你的问题,现在你可以返回的URL在你的方法一做你的控制器:'@ url = get_item_info(@ product.id)' – Kaeros 2013-02-25 18:59:45

+0

为什么要为'ProdInfo'命名模块需要'get_prod_info'?这些名字不匹配很奇怪。您是否记得在更换模块后重新启动服务器? – jdl 2013-02-25 19:13:39

+0

我的lib文件被称为get_prod_info.rb,它的标题应该与我的模块相同吗?是的,确保重新启动我的服务器后,对我的模块进行更改 – Yogzzz 2013-02-25 19:15:17

回答

0

这实质上是Kaeros的评论扩展到两个地方的代码。

你只需要将变量保存在你的控制器而不是你的lib文件夹中。你的lib文件不应该知道你的模型的需求,并且在不知道在哪里或如何保存它的情况下返回一个值就会很高兴。

module ProdInfo 
    def get_item_info(id) 
    # in your comment you said you have multiple values you need to access from here 
    # you just need to have it return a hash so you can access each part in your view 

    # gather info 
    { :inventory => 3, :color => "blue", :category => "tool"} # this is returned to the controller 
    end 
end 

Rails 3中也有一个配置变量,它允许您指定的路径来加载,我相信默认包含的lib路径。这意味着您不需要所有require条目。你可以拨打Module#method对。

class RecommendationsController < ApplicationController 
    # require 'get_prod_info' 
    # include ProdInfo 
    # => In Rails 3, the lib folder is auto-loaded, right? 

    def index 
    @product = Product.find(params["product_id"]) 
    @item_info = ProdInfo.get_item_info(@product.id) # the hash you created is saved here 
    end 
end 

这里是你如何可以在视图中使用它:

# show_item.text.erb 

This is my fancy <%= @item_info[:color] %> item, which is a <%= @item_info[:type] %>. 

I have <%= @item_info[:inventory] %> of them. 
+0

我有我的'get_item_info'方法中定义的多个变量,我需要在我的视图中使用。 – Yogzzz 2013-02-25 19:33:51

+0

所以只要将'get_item_info'打包成一个散列,然后你可以在视图中访问它。我会更新代码。 – jstim 2013-02-25 19:36:05

相关问题