這實質上是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