Ruby on Rails: How to join two tables

后端 未结 1 1752
野趣味
野趣味 2020-12-14 12:58

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 h

相关标签:
1条回答
  • 2020-12-14 13:29

    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 %>
    
    0 讨论(0)
提交回复
热议问题