来自助手的 link_to
想知道如何做到这一点。
我有一个月份助手,想要呈现每个月的列表。
如果您单击月份,它将传递数值。我想生成一个像这样的列表,
Choose a month
January - February - March - April - May.....
即链接。我的帮手长这个样子。
MONTHLIST = [
[ "January", "1" ],
[ "February", "2" ],
[ "March", "3" ]
].freeze
如何使用 link_to 获取名称和链接作为值。即三月#3。
Wondering how to do this.
I have a month helper and want to render a list of each month.
If you click on the month it would then pass the number value . I want to produce a list like this
Choose a month
January - February - March - April - May.....
That are links. My helper looks like this.
MONTHLIST = [
[ "January", "1" ],
[ "February", "2" ],
[ "March", "3" ]
].freeze
How do I use link_to to get the names and link be the value. i.e #3 for march.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个简单的方法:将视图传递给
view 中的
helper 。
。
在你的帮手中
Here's a simple approach: pass the view to the helper
in your view
.
.
in your helper
如果我完全理解您的意思,您的意思是您想调用辅助模块中的
link_to
方法,对吗?然后,当调用辅助方法时,会将link_to
方法的结果返回给调用它的视图。如果这就是您想要的,我正在努力解决类似的问题,因为辅助模块无法访问
link_to
方法,除非通过ActionView::Helpers::URLHelper
实例这是为了响应您的服务请求而创建的。我假设可以通过 Rails 系统变量访问该对象,但我不知道它可能是什么。想法?暂时,我的答案是仅在视图文件中使用
link_to
方法。您的帮助程序文件将如下所示:然后您的视图文件将这样调用帮助程序方法:(
是的,这可能是比您需要的更详细的代码。它可以被缩写。)
If I understand you completely, you mean that you want to call the
link_to
method in your helper module, right? Then the helper method, when called, will return the result of thelink_to
method to whichever view called it.If that's what you want, I'm butting my head against a similar problem because the helper module cannot access the
link_to
method except through theActionView::Helpers::URLHelper
instance that was created in response to your service request. I assume that this object can be accessed through a Rails system variable, but I am at a loss as to what that might be. Thoughts?For the interrim, my answer is to use the
link_to
method only within your view file. Your helper file would look something like this:Then your view file would call the helper method thus:
(Yes, that was probably a more verbose code than you needed. It could have been abbreviated.)
另一种选择!如下:
从
link_to
方法创建一个 Proc 对象,然后将其作为参数从视图传递给帮助器。它的外观如下...您的视图文件:
您的帮助程序文件:
对于 proc.call 语句中的第二个参数,使用您通常在
link_to
方法中设置 url 的内容,例如:controller => [x],:动作=> [y]
。回顾一下,您正在做的是创建一个包装您的方法的 Proc,然后将该包装的方法发送给您的帮助程序,该帮助程序将返回您的超链接的 html 代码,您的 .html.erb 文件将将该代码打印到您的 html 页面。
An alternative! Here goes:
Make a Proc object out of the
link_to
method, then pass it from your view to the helper as an argument. Here's how it will look...Your view file:
Your helper file:
For the second arg in your proc.call statement, use what you'd normally use to set the url in your
link_to
method, e.g.:controller => [x], :action => [y]
.To recap, what you're doing is making a Proc that wraps your method, then sending that wrapped method to your helper, which will return html code for your hyperlink, which your .html.erb file will print to your html page.