7

I have an index page that I want to show all the users' profile and their associated photos. I'm using the plugin Paperclip for the photos. In the Profiles controller, I have the instance variable @profile but it shows me the table in the profiles table only and not the photos table.

@profile = Profile.find(:all, :include => :photos,
  :joins => "INNER JOIN photos ON photos.profile_id = profiles.id")

The models are shown below:

class Profile < ActiveRecord::Base
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :profile
end

What I want to be able to show in the View is something like:

  • John's profile (e.g., name, age, sex) - John's picture (e.g., only one picture shown)
  • Mary's profile here - Mary's picture shown here
  • Bob's profile here - Bob's picture shown here
2
  • If a Profile has many Photos, how do you determine which picture to show for a particular Profile? Should this be a one-to-one relationship? (There would be a few different ways to do that in the database - Profile could have a foreign key for profile_photo, for instance, or there could be a boolean column in Photos indicating whether a particular photo is intended to be the "primary") Apr 19, 2009 at 2:18
  • Yes, I have a boolean column called primary. If it's set to 1, it should show the photo.
    – Max
    Apr 19, 2009 at 6:46

1 Answer 1

15

I've edited my answer to reflect your extra comments.

First of all, you shouldn't need the :joins parameter; :include => :photos should handle the join "behind the scenes" for you.

Here's one way to do what you're asking about.

(in the models)

class Profile < ActiveRecord::Base
  has_many :photos
  has_one :primary_photo, :class_name => "Photo", :conditions => {:primary => true}
end

(in the controller)

@profiles = Profile.find(:all, :include => :primary_photo)

(in the view)

<% @profiles.each do |profile| %>
  Name: <%= profile.name %>
  Age: <%= profile.age %>
  Photo: <%= image_tag profile.primary_photo.url %>
<% end %>
2
  • I have a boolean column called primary in the Photos table. Is there a way to display the photo only if the primary column is set to 1? Adding the line <%= if photo.primary = 1 %> after the profile.photos.each tag doesn't seem to work.
    – Max
    Apr 19, 2009 at 6:52
  • Ok, it's working now. I should be using tinyint instead of int for the primary column in the database.
    – Max
    Apr 19, 2009 at 19:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.