0

I have a div, and I want it to be a link to other page. Usually we do it like this link_to link.

<% for post in @posts %>
   <%= link_to "Post", post %> # -> or <%= link_to(post) %>
<% end %>

But i need to whole div to be a link with js. So, i did:

<% for post in @posts %>
    <div class="post-on-main-page-<%= div_count %>" >
        <script>
           $(".post-on-main-page-<%= div_count %>").click(function(){
                window.location.href = "<%= link_to(post) %>";
              });
        </script>
    </div>
<% end %>

But i doesn't work.

I need to window.location.href = "<%= link_to(post) %>"; where post is a parameter, to give me a link to that post.

So how I can make this to work?

3
  • Why not just add a data attribute to the div and use that value to do your redirecting? Commented Aug 16, 2016 at 21:29
  • try this `window.location.href = " #{ link_to(post) }"; Commented Aug 16, 2016 at 21:33
  • @BrenoPerucchi no that is broken Commented Aug 16, 2016 at 21:34

2 Answers 2

1

link_to will generate a full <a> element

You should use post_path(post) or post_url(post) instead if you just want the path or url

Sign up to request clarification or add additional context in comments.

Comments

0

You can pass a block to link_to helper like

<% @posts.each do |post| %>
  <%= link_to post do %>
    <div class="post-on-main-page">
     <!-- Fill in your content -->
    </div>
  <% end %>
<% end %>

This will generate a div which will link to posts#show page.

1 Comment

Yes, I aware of that. But this is bad decision for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.