Andrey Drozdov
Andrey Drozdov

Reputation: 591

Rails, add ruby parameter to javascript

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?

Upvotes: 0

Views: 38

Answers (2)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

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.

Upvotes: 0

Mulan
Mulan

Reputation: 135197

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

Upvotes: 1

Related Questions