我在我的帖子/索引 View 上使用了一个 link_to 标签,并希望使用一个 anchor 将它链接到我的帖子/显示/id View ,使其向下滚动到评论表单。出于某种原因,我无法让 anchor 工作。这是我的代码:
在帖子/索引中
<%= link_to 'Add a Comment', post, :anchor => 'comment_form' %>
这无法将 # 符号附加到链接的末尾,因此它只是 localhost:3000/posts/id。
我还为 link_to 尝试了许多变体,包括:
<%= link_to 'Add a Comment', post(:anchor => 'comment_form' %>
和
<%= link_to 'Add a Comment', :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_form' %>
但我没有运气。
这是我的帖子#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
这是我希望 anchor 滚动到的帖子/显示 View :
<h2><a name="comment_form" id="comment_form">Add a comment:</a></h2>
此外,如果我链接到索引页面上的某些内容,则上述任何内容都有效,因为我可以看到哈希 # 已附加到输出的 url。由于某种原因,它在尝试链接到显示页面时不起作用。有什么帮助吗?
最佳答案
尝试这个:
link_to('Add a comment', post_path(post, :anchor => 'comment_form'))
link_to
的第二个参数通常按原样传递给 url_for
,第三个参数用作 <a>
的属性散列最终生成的元素。所以在你的第一个例子中,你传递了一个
Post
object 作为第二个参数,一个 hash 作为第三个参数。只有Post
将传递给 url_for
.它永远不会看到包含 :anchor
的哈希值选项,因此您不会在生成的 URL 末尾看到 anchor 。 (但您可能会在生成的 anchor="comment_form"
元素上看到 <a>
属性。)您的第二个示例在语法上不正确。我想这会导致错误。
你的第三个例子......应该有效。我不知道为什么它没有:-)
关于ruby-on-rails - Rails 3.1.3 使用 anchor 属性和 link_to 标签从帖子/索引到帖子/显示/id 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9251606/