Using link_to in a class in a Rails helper

只愿长相守 提交于 2019-12-21 09:06:35

问题


I have a rails helper using the structore below, but when I use it I get the message

undefined method 'link_to'

The helper is arranged as:

module MyHelper

  class Facet

    def render_for_search
      link_to("Value", params)
    end
  end

  class FacetList
    attr_accessor :facets

    def initialize
      #Create facets
    end

    def render_for_search
      result = ""
      facets.each do |facet|
        result << facet.render_for_search
      end
      result
    end
  end
end

回答1:


This is because within the Class Facet you don't have access to the template binding. In order to call the render_for_search method you probably do something like

<%= Facet.new.render_for_search %>

Just override your initialize method to take the current context as argument. The same applies to the params hash.

class Facet
  def initialize(context)
    @context = context
  end
  def render_for_search
    @context.link_to("Value", @context.params)
  end
end

Then call

<%= Facet.new(self).render_for_search %>

Otherwise, define the render_for_search method directly within the MyHelper module and don't wrap it into a class.




回答2:


Try using this:

self.class.helpers.link_to

Because link_to is not defined in your current scope.

The above will work for a controller, but I'm guessing it will work inside another helper as well. If not then try:

include ActionView::Helpers::UrlHelper

At the top of your helper.



来源:https://stackoverflow.com/questions/2023751/using-link-to-in-a-class-in-a-rails-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!