Search code examples
ruby-on-railsanchorlink-torails-3.1

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. 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?


Solution

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