How to Create an Anchor and Redirect to This Specific Anchor in Ruby on Rails

How to create an anchor and redirect to this specific anchor in Ruby on Rails

It looks like you want to use the link_to code that you have in your question. Then in your list of comments you have to make sure that you have an anchor tag named the same thing in the link.

So this:

 <%= link_to 'Your comment', post_path(@comment.post) + "#comment_#{@comment.id.to_s}" %>

will generate something like this

 <a href="localhost:3000/posts/2#1comment_234">Your comment</a>

/* html code */

<a name="comment_1234">This is a comment</a>

You have to manually tack on the #comment_ otherwise the link_to method thinks that the :anchor attribute that you are passing it is for that tag.

How to add an anchor to redirect_to :back

I ended up using Javascript instead.

posts_controller.rb

def vote
@post = Post.find(params[:id])
#voting logic
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end

posts/_post.html.erb

<div class="post_partial" id="post_<%= post.id %>">
<%= post.content %>
<div id="vote_button_<%= post.id %>">
<%= link_to "up", vote_path, method: "post", remote: true %>
</div>
</div>

posts/vote.js.erb

$('#post_<%= @post.id %>').html('<%= j render @post %>');

Rails 4 - Redirect to anchor section of a page after login

Try using

user_new_path + '#profile_pic'

in after_sign_in_path_for method.

Hope that helps!



Related Topics



Leave a reply



Submit