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,但无法弄清楚出了什么问题.
Ris*_*ogi 19
这是因为,ActionView urlhelpers仅适用于Views,而不适用于lib目录.
link_to方法可以在ActionView :: Helpers :: UrlHelper模块中找到,另外还有你
试试吧.
class Facet include ActionView::Helpers::UrlHelper ... end
简单地包括帮助者不会让你更进一步.帮助者假设他们在请求的上下文中,以便他们可以读出域名等等.
反过来做; 在应用程序助手中包含您的模块,或类似的东西.
# 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)