Rails 3.1.3使用锚属性和链接_to标签从帖子/索引到帖子/显示/ID无效 [英] Rails 3.1.3 using anchor attribute with link_to tag from posts/index to posts/show/id not working
问题描述
我在帖子/索引视图上使用link_to标记,并希望通过锚使其链接到我的帖子/显示/id视图,以使其向下滚动到评论表单.由于某种原因,我无法让锚工作.这是我的代码:
I am using a link_to tag on my posts/index view and want to link it to my posts/show/id view with an anchor that makes it scroll down to the comments form. For some reason I can't get the anchor to work. Here is my code:
帖子/索引中
<%= link_to 'Add a Comment', post, :anchor => 'comment_form' %>
这无法将#符号附加到链接的末尾,因此它只是localhost:3000/posts/id. 我还尝试了link_to的许多变体,包括:
This fails to append the # sign to the end of the link, so it is just localhost:3000/posts/id. I have also tried many variations for link_to, including:
<%= link_to 'Add a Comment', post(:anchor => 'comment_form' %>
和
<%= link_to 'Add a Comment', :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_form' %>
但是我没有运气.
这是我的帖子#显示操作:
Here is my posts#show action:
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
这是我希望锚点滚动到的帖子/显示视图:
and here is the posts/show view where I want the anchor to scroll to:
<h2><a name="comment_form" id="comment_form">Add a comment:</a></h2>
此外,如果我链接到索引页面上的某些内容,则上述任何方法均有效,因为我可以看到哈希值#已附加到输出的url中.由于某些原因,当尝试链接到显示页面时,它不起作用.有什么帮助吗?
Furthermore, any of the above works if I am linking to something on the index page, as I can see the hash # has been appended to the outputted url. For some reason it is not working when trying to link to the show page. Any help with this?
推荐答案
尝试一下:
link_to('Add a comment', post_path(post, :anchor => 'comment_form'))
link_to
的第二个参数通常按原样传递给url_for
,第三个参数用作最终生成的<a>
元素的属性哈希.
The second argument to link_to
is typically passed as-is to url_for
, and the third argument is used as an attributes hash for the <a>
element that ultimately gets generated.
因此,在第一个示例中,您将传递Post
对象作为第二个参数,并传递一个哈希作为第三个参数.只有Post
会被传递给url_for
.它永远不会看到包含:anchor
选项的哈希,因此您不会在生成的URL的末尾看到锚点. (但是您可能会在生成的<a>
元素上看到一个anchor="comment_form"
属性.)
So in your first example, you're passing a Post
object as the second argument and a hash as the third argument. Only the Post
would be passed to url_for
. It never sees the hash containing the :anchor
option, so you wouldn't see the anchor at the end of the generated URL. (But you would probably see an anchor="comment_form"
attribute on the generated <a>
element.)
您的第二个示例在语法上不正确.我想这会导致错误.
Your second example is syntactically incorrect. I imagine that resulted in an error.
您的第三个示例...应该有用.我不确定为什么没有:-)
Your third example...should've worked. I'm not sure why it didn't :-)
这篇关于Rails 3.1.3使用锚属性和链接_to标签从帖子/索引到帖子/显示/ID无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!