【问题标题】:undefined method 'link_to'未定义的方法'link_to'
【发布时间】:2010-12-30 06:24:08
【问题描述】:

我正在编写一个 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,但不知道出了什么问题。

【问题讨论】:

    标签: ruby-on-rails link-to url-helper


    【解决方案1】:

    仅仅包括助手并不能让你走得更远。助手假设他们在请求的上下文中,以便他们可以读出域名等。

    反过来做;将您的模块包含在应用程序帮助程序或类似的东西中。

    # 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
    

    【讨论】:

      【解决方案2】:

      试试这个:

      ActionController::Base.helpers.link_to
      

      【讨论】:

        【解决方案3】:

        这是因为,ActionView urlhelpers 只对 View 可用,而不是在你的 lib 目录中。

        link_to 方法在 ActionView::Helpers::UrlHelper 模块中,加上你自己

        所以试试这个。

        类方面 包括 ActionView::Helpers::UrlHelper ... 结尾

        【讨论】:

        • 我不能肯定地说,但是当我这样做时,我的观点似乎被打破了。不知道为什么,但我怀疑这会导致一些棘手的事情发生。
        • 在 Rails 3.2 中,这不起作用。这个是:ActionController::Base.helpers.link_to
        • 我在 2009 年回答了这个问题,我认为当时还没有稳定版本的 Rails 3(没有 3.1,没有 3.2)。
        猜你喜欢
        • 2015-10-18
        • 2012-08-12
        • 1970-01-01
        • 1970-01-01
        • 2018-11-22
        • 2015-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多