Rails 3.1.3 using anchor attribute with link_to tag from posts/index to posts/show/id not working

心已入冬 提交于 2019-12-12 08:48:45

问题


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:

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. I have also tried many variations for link_to, including:

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

  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. For some reason it is not working when trying to link to the show page. Any help with this?


回答1:


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.

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 :-)



来源:https://stackoverflow.com/questions/9251606/rails-3-1-3-using-anchor-attribute-with-link-to-tag-from-posts-index-to-posts-sh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!