代码之家  ›  专栏  ›  技术社区  ›  Mike Sutton

未定义的方法“链接到”

  •  18
  • Mike Sutton  · 技术社区  · 15 年前

    我正在编写RubyonRails库模块:

    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_进行搜索时,我得到了错误

    undefined method 'link_to'
    

    我试过直接要求url_helper,但不知道出了什么问题。

    3 回复  |  直到 15 年前
        1
  •  19
  •   Rishav Rastogi    15 年前

    这是因为,actionview urlhelpers只对视图可用,而不在lib目录中。

    在ActionView::Helpers::UrlHelper模块以及您的wou中可以找到指向方法的链接

    试试这个。

     class Facet
       include ActionView::Helpers::UrlHelper
    ...
    end
    
        2
  •  24
  •   khelll    15 年前

    试试这个:

    ActionController::Base.helpers.link_to
    
        3
  •  5
  •   August Lilleaas    15 年前

    简单地包括助手并不能让你走得更远。帮助者假定他们在请求的上下文中,这样他们就可以读取域名等等。

    换一种方式来做;将模块包含在应用程序帮助器中,或者类似的方法。

    # 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