Rails查看Helper函数和link_to函数

Pau*_*aul 4 ruby ruby-on-rails

我正在尝试创建一个辅助函数(例如,在application_helper.rb)中生成link_to基于传递给辅助函数的参数.如果我将链接放在ERB文件中,它的格式为:

<%= link_to 'Some Text', { :controller => 'a_controller', :action => 'an_action' } %>
Run Code Online (Sandbox Code Playgroud)

在辅助函数中,Text,Controller和Action都被传入或计算.辅助函数中的代码是:

params = "{ :controller => '#{controller}', :action => '#{action_to_take}'}"
html   = "#{link_to some_text, params }<p />"
return html
Run Code Online (Sandbox Code Playgroud)

生成的链接具有正确的文本,但参数实际上是params字符串的内容.

如何获取params要评估的字符串(因为它在ERB文件中)?

gun*_*unn 10

我觉得你脑子里的事情过于复杂.除非你试图做一些非常奇怪的事情(并且不可取),否则这会有效:

def link_helper text, controller, action
  link_to text, :controller => controller, :action => action
end
Run Code Online (Sandbox Code Playgroud)

虽然,你可以看到它不值得它成为一个帮手 - 它几乎不比它的包装功能简单,而且灵活性要低得多.

link_to帮助器返回一个字符串,因此以您想要的方式使用它非常简单:

def link_helper text
  # some helper logic:
  controller = @controller || "pages"
  action     = @action     || "index"

  # create the html string:
  html = "A link to the #{controller}##{action} action:"
  html << link_to(text, :controller => controller, :action => action)
  html # ruby does not require explicit returns
end
Run Code Online (Sandbox Code Playgroud)