从documentation(以及Google)可以明显看出如何生成与细分的链接,例如podcast/5#comments
。您只需将:anchor
的值传递给link_to
。
我担心的是生成<a name="comments">Comments</a>
标签的简单任务,即第一个链接的目的地。
我尝试了以下内容,虽然它们似乎有用,但标记不符合我的预期:
link_to "Comments", :name => "comments"
link_to "Comments", :anchor => "comments"
我想我错过了一些明显的东西。感谢。
答案 0 :(得分:54)
你对Ruby的语法糖(Rails大量使用)感到困惑。在回答你的问题之前,让我简要解释一下。
当ruby函数接受一个哈希的参数时:
def foo(options)
#options is a hash with parameters inside
end
你可以'忘记'把括号/括号括起来,并像这样调用它:
foo :param => value, :param2 => value
Ruby会填补空白并理解你要完成的是:
foo({:param => value, :param2 => value})
现在,对于您的问题:link_to
需要两个可选哈希值 - 一个称为options
,另一个称为html_options
。你可以想象它是这样定义的(这是一个近似值,它要复杂得多)
def link_to(name, options, html_options)
...
end
现在,如果你这样调用它:
link_to 'Comments', :name => 'Comments'
Ruby会有点困惑。它会尝试为你“填空”,但不正确:
link_to('Comments', {:name => 'Comments'}, {}) # incorrect
它会认为name => 'Comments'
部分属于选项,而不属于html_options
!
你必须自己填补空白来帮助红宝石。将所有括号放在适当位置,它将按预期运行:
link_to('Comments', {}, {:name => 'Comments'}) # correct
如果需要,您实际上可以删除最后一组括号:
link_to("Comments", {}, :name => "comments") # also correct
为了使用html_options,您必须保留第一组括号。例如,您需要为包含确认消息和名称的链接执行此操作:
link_to("Comments", {:confirm => 'Sure?'}, :name => "comments")
其他rails帮助器具有类似的结构(即form_for
,collection_select
),因此您应该学习这种技术。有疑问,只需添加所有括号。
答案 1 :(得分:14)
答案 2 :(得分:0)
<%= link_to('new button', action: 'login' , class: "text-center") %>
为login.html i.g
创建了一个锚标记<a href="login.html" class = "text-center"> new button </a>
和
<a href="admin/login.html" class = "text-center"> new button </a>
使用
<%= link_to('new button', controller: 'admin',
action: 'login' , class: "text-center") %>