Ruby on Rails: How to join two tables

北城余情 提交于 2019-12-18 01:13:09

问题


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

回答1:


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 %>


来源:https://stackoverflow.com/questions/764538/ruby-on-rails-how-to-join-two-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!