这实质上是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.
我想你的问题,现在你可以返回的URL在你的方法一做你的控制器:'@ url = get_item_info(@ product.id)' – Kaeros 2013-02-25 18:59:45
为什么要为'ProdInfo'命名模块需要'get_prod_info'?这些名字不匹配很奇怪。您是否记得在更换模块后重新启动服务器? – jdl 2013-02-25 19:13:39
我的lib文件被称为get_prod_info.rb,它的标题应该与我的模块相同吗?是的,确保重新启动我的服务器后,对我的模块进行更改 – Yogzzz 2013-02-25 19:15:17