Ruby on Rails:如何连接两个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/764538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:09:30  来源:igfitidea点击:

Ruby on Rails: How to join two tables

ruby-on-railsjoinactiverecord

提问by Max

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.

我有一个索引页面,我想显示所有用户的个人资料及其相关照片。我正在为照片使用插件 Paperclip。在 Profiles 控制器中,我有实例变量 @profile 但它只向我显示了配置文件表中的表,而不是照片表。

@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
  • 约翰的个人资料(例如姓名、年龄、性别) - 约翰的照片(例如,仅显示一张照片)
  • 此处显示玛丽的个人资料 - 此处显示玛丽的照片
  • 此处是鲍勃的个人资料 - 此处显示鲍勃的照片

回答by Greg Campbell

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

我已经编辑了我的答案以反映您的额外评论。

First of all, you shouldn't need the :joinsparameter; :include => :photosshould handle the join "behind the scenes" for you.

首先,你不应该需要:joins参数;:include => :photos应该为您处理“幕后”加入。

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