[英]Rails 3.1.3 using anchor attribute with link_to tag from posts/index to posts/show/id not working
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. 我在我的帖子/索引视图上使用了link_to标签,并希望将其链接到我的帖子/ show / id视图,并使用一个锚点向下滚动到评论表单。 For some reason I can't get the anchor to work.
出于某种原因,我无法让锚点工作。 Here is my code:
这是我的代码:
In posts/index 在帖子/索引中
<%= link_to 'Add a Comment', post, :anchor => 'comment_form' %>
This fails to append the # sign to the end of the link, so it is just localhost:3000/posts/id. 这无法将#符号附加到链接的末尾,因此它只是localhost:3000 / posts / id。 I have also tried many variations for link_to, including:
我也为link_to尝试过很多变种,包括:
<%= link_to 'Add a Comment', post(:anchor => 'comment_form' %>
and 和
<%= link_to 'Add a Comment', :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_form' %>
but I've had no luck. 但我没有运气。
Here is my posts#show action: 这是我的帖子#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>
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. 此外,如果我链接到索引页面上的某些内容,上面的任何一个都可以工作,因为我可以看到散列#已被附加到输出的url。 For some reason it is not working when trying to link to the show page.
由于某种原因,在尝试链接到节目页面时它无法正常工作。 Any help with this?
对此有何帮助?
Try this: 尝试这个:
link_to('Add a comment', post_path(post, :anchor => 'comment_form'))
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. link_to
的第二个参数通常按原样传递给url_for
,第三个参数用作最终生成的<a>
元素的属性哈希。
So in your first example, you're passing a Post
object as the second argument and a hash as the third argument. 因此,在您的第一个示例中,您将
Post
对象作为第二个参数传递,并将散列作为第三个参数传递。 Only the Post
would be passed to url_for
. 只有
Post
会被传递给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. 它永远不会看到包含
:anchor
选项的哈希,因此您不会在生成的URL的末尾看到锚点。 (But you would probably see an anchor="comment_form"
attribute on the generated <a>
element.) (但你可能会在生成的
<a>
元素上看到一个anchor="comment_form"
属性。)
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 :-)
我不确定为什么没有:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.