未定义的方法'link_to'

Mik*_*ton 18 ruby-on-rails link-to url-helper

我正在写一个ruby-on-rails库模块:

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
Run Code Online (Sandbox Code Playgroud)

当我调用render_for_search时,我得到了错误

undefined method 'link_to'
Run Code Online (Sandbox Code Playgroud)

我已经尝试过直接要求url_helper,但无法弄清楚出了什么问题.

khe*_*lll 24

试试这个:

ActionController::Base.helpers.link_to
Run Code Online (Sandbox Code Playgroud)


Ris*_*ogi 19

这是因为,ActionView urlhelpers仅适用于Views,而不适用于lib目录.

link_to方法可以在ActionView :: Helpers :: UrlHelper模块中找到,另外还有你

试试吧.

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

  • 在 Rails 3.2 中,这不起作用。这个的作用是: ActionController::Base.helpers.link_to (2认同)

Aug*_*aas 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
Run Code Online (Sandbox Code Playgroud)