Rails 3.1.3使用anchor属性和posts_to标签从posts/index到posts/show/id不起作用

kwy*_*g11 7 anchor ruby-on-rails link-to rails-3.1

我在我的帖子/索引视图上使用了link_to标签,并希望将其链接到我的帖子/ show/id视图,并使用一个锚点向下滚动到评论表单.出于某种原因,我无法让锚点工作.这是我的代码:

在帖子/索引中

<%= link_to 'Add a Comment', post, :anchor => 'comment_form' %>
Run Code Online (Sandbox Code Playgroud)

这无法将#符号附加到链接的末尾,因此它只是localhost:3000/posts/id.我也为link_to尝试过很多变种,包括:

<%= link_to 'Add a Comment', post(:anchor => 'comment_form' %>
Run Code Online (Sandbox Code Playgroud)

<%= link_to 'Add a Comment', :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_form' %>
Run Code Online (Sandbox Code Playgroud)

但我没有运气.

这是我的帖子#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
Run Code Online (Sandbox Code Playgroud)

这里是我希望锚点滚动到的帖子/显示视图:

<h2><a name="comment_form" id="comment_form">Add a comment:</a></h2>
Run Code Online (Sandbox Code Playgroud)

此外,如果我链接到索引页面上的某些内容,上面的任何一个都可以工作,因为我可以看到散列#已被附加到输出的url.由于某种原因,在尝试链接到节目页面时它无法正常工作.对此有何帮助?

Bra*_*dan 14

试试这个:

link_to('Add a comment', post_path(post, :anchor => 'comment_form'))
Run Code Online (Sandbox Code Playgroud)

第二个参数link_to通常按原样传递给url_for,第三个参数用作<a>最终生成的元素的属性哈希.

所以在你的第一个例子中,你将一个Post对象作为第二个参数传递,并将一个哈希作为第三个参数传递.只有Post传递给url_for.它永远不会看到包含该:anchor选项的哈希,因此您不会在生成的URL的末尾看到锚点.(但您可能会anchor="comment_form"在生成的<a>元素上看到一个属性.)

你的第二个例子在语法上是不正确的.我想这导致了一个错误.

你的第三个例子......应该有效.我不确定为什么没有:-)