22

我正在编写一个 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

当我调用 render_for_search 我得到错误

undefined method 'link_to'

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

4

3 回答 3

25

Try this:

ActionController::Base.helpers.link_to
于 2009-12-27T13:33:12.403 回答
23

This is because, ActionView urlhelpers are only available to the Views, not in your lib directory.

the link_to method is found in the ActionView::Helpers::UrlHelper module, plus you wou

so try this.

 class Facet
   include ActionView::Helpers::UrlHelper
...
end
于 2009-12-27T13:27:39.777 回答
5

Simply including the helper doesn't get you much further. The helpers assume that they are in the context of a request, so that they can read out the domain name and so on.

Do it the other way around; include your modules in the application helper, or something like that.

# 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
于 2009-12-27T13:38:26.790 回答