在Rails帮助器中的类中使用link_to [英] Using link_to in a class in a Rails helper

查看:140
本文介绍了在Rails帮助器中的类中使用link_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rails助手使用structore下面,但是当我使用它,我得到的消息

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

undefined method 'link_to'

帮助者排列如下:

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


推荐答案

这是因为在类构面中,您无权访问模板绑定。
为了调用 render_for_search 方法,您可能需要执行

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 %>

只需覆盖 initialize 当前上下文作为参数。
这同样适用于params哈希。

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

然后调用

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

否则,直接在 render_for_search MyHelper 模块,不要将其包装到类中。

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

这篇关于在Rails帮助器中的类中使用link_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆