【问题标题】:Rails 3.1.3 using anchor attribute with link_to tag from posts/index to posts/show/id not workingRails 3.1.3使用带有link_to标签的锚属性从posts/index到posts/show/id不起作用
【发布时间】:2012-03-04 07:53:18
【问题描述】:

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

在帖子/索引中

<%= 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

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

<h2><a name="comment_form" id="comment_form">Add a comment:</a></h2>

此外,如果我链接到索引页面上的某些内容,上述任何一项都有效,因为我可以看到哈希 # 已附加到输出的 url。由于某种原因,它在尝试链接到显示页面时不起作用。有什么帮助吗?

【问题讨论】:

    标签: ruby-on-rails anchor link-to rails-3.1


    【解决方案1】:

    试试这个:

    link_to('Add a comment', post_path(post, :anchor => 'comment_form'))
    

    link_to 的第二个参数通常按原样传递给 url_for,第三个参数用作最终生成的 &lt;a&gt; 元素的属性哈希。

    因此,在您的第一个示例中,您将 Post 对象作为第二个参数传递,并将哈希作为第三个参数传递。只有Post 会被传递给url_for。它永远不会看到包含 :anchor 选项的散列,因此您不会在生成的 URL 的末尾看到锚点。 (但您可能会在生成的 &lt;a&gt; 元素上看到 anchor="comment_form" 属性。)

    您的第二个示例在语法上不正确。我想这会导致错误。

    您的第三个示例...应该有效。我不知道为什么没有:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多