9

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
Mike Sutton
  • 4,191
  • 4
  • 29
  • 42

2 Answers2

7

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.

mopoke
  • 10,555
  • 1
  • 31
  • 31
  • This won't work because `params` is not defined within the class scope. – Simone Carletti Jan 07 '10 at 23:49
  • 1
    You can pass `params` (or just the a particular param via `params[:month]` for example) to your helper method from wherever its called, i.e. `def render_for_search(params)` which enforces the method requiring 1 argument. – Michael De Silva Apr 28 '12 at 11:15
3

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.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364