2009-12-27 50 views
12

我正在寫的Ruby-on-軌庫模塊:未定義的方法 '的link_to'

module Facets 

    class Facet 
    attr_accessor :name, :display_name, :category, :group, :special 

    ... 

    URI = {:controller => 'wiki', :action => 'plants'} 
    SEARCH = {:status => WikiLink::CURRENT} 

    #Parameters is an hash of {:field => "1"} values 
    def render_for_search(parameters) 
    result = link_to(display_name, URI.merge(parameters).merge({name => "1"})) 
    count = WikiPlant.count(:conditions => (SEARCH.merge(parameters.merge({name => "1"})))) 
    result << "(#{count})" 
    end 
    end 

    ... 

end 

當我打電話render_for_search我得到的錯誤

undefined method 'link_to' 

我試過直接要求url_helper但無法弄清楚發生了什麼問題。

回答

16

這是因爲,ActionView urlhelpers只對視圖有效,不在你的lib目錄中。

的方法的link_to在::的ActionView ::助手模塊UrlHelper發現,再加上你WOU

這樣試試這個。

 
class Facet 
    include ActionView::Helpers::UrlHelper 
... 
end 
+1

有人可以解釋爲什麼這被拒絕而沒有評論? – GSP 2013-01-23 17:54:56

+0

我不能肯定地說,但當我這樣做時,我的觀點似乎破裂了。不知道爲什麼,但我懷疑這會導致一些棘手的事情發生。在Rails 3.2中使用 – bchurchill 2013-01-31 08:07:05

+0

,這不起作用。這個可以:ActionController :: Base.helpers.link_to – GregT 2013-02-08 06:57:23

20

試試這個:

ActionController::Base.helpers.link_to 
5

只要引入助手沒有讓你更進一步。助手假定他們處於請求的上下文中,以便他們可以讀出域名等。

以相反的方式去做;將你的模塊包含在應用程序助手中,或類似的東西。

# lib/my_custom_helper.rb 
module MyCustomHelper 
    def do_stuff 
    # use link_to and so on 
    end 
end 

# app/helpers/application_helper.rb 
module ApplicationHelper 
    include MyCustomHelper 
end