Search code examples
ruby-on-railsrubyruby-on-rails-3facebox

how to individualize each post? (Ruby on Rails)


On each user profile (localhost:3000/users/username), there's a listing of posts that the user has made. I implemented facebox which is a jQuery-based lightbox to display images when clicked on. This is the code that I'm using for that:

<a href=<%= post.image_url %> rel="facebox"><%= image_tag post.image_url(:thumb).to_s %></a>

The problem is that, if a user has made 5 posts, the same image is repeated 5 times when clicked on to display in facebox.

This is my show.html.erb where I render in @posts

<% provide(:title, @user.name) %>
<div class="row">
  <aside class="span4">
    <section>
      <h1>
        <%= gravatar_for @user %>
        <%= @user.name %>
      </h1>
    </section>
       <br>
  </aside>
 <br>


  <div class="span10">
    <%= render 'follow_form' if signed_in? %>
    <% if @user.posts.empty? %>
<h3>Browse</h3>
<% end %>
    <% if @user.posts.any? %>
      <ol class="posts">
        <%= render @posts %>

      </ol>

      <%= will_paginate @posts %>
    <% end %>
  </div>
</div>

and here's the _post.html.erb

<script src="/jquery.js" type="text/javascript"></script>
<link href="/src/facebox.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="/src/facebox.js" type="text/javascript"></script> 
<script language="javascript">

 jQuery(document).ready(function($) {
  $('a[rel*=facebox]').facebox() 
}) 

</script>


    <li>
      <span class="content"><%= simple_format(post.content) %></span>
      <% if post.image.present? %>
      <a href=<%= post.image_url %> rel="facebox"><%= image_tag post.image_url(:thumb).to_s %></a>
      <br>
      <% else %>
      <% end %>
      <span class="timestamp">
        Posted <%= time_ago_in_words(post.created_at) %> ago.
      </span>
</li>

Solution

  • The javascript in _post.html.erb is included and executed once for each post. Therefore, if the user has five posts, you are initializing facebox five times. Move the script tags out of the partial. Instead, place them in show.html.erb so that they will only execute once for the entire page.