Ruby on Rails:如何连接两个表 [英] Ruby on Rails: How to join two tables
问题描述
我有一个索引页面,我想显示所有用户的个人资料及其相关照片.我正在为照片使用插件 Paperclip.在 Profiles 控制器中,我有实例变量 @profile 但它仅向我显示配置文件表中的表,而不是照片表.
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")
模型如下:
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 的个人资料(例如姓名、年龄、性别)- John 的照片(例如,只显示了一张照片)
- 此处是玛丽的个人资料 - 此处显示的是玛丽的照片
- 此处是鲍勃的个人资料 - 此处显示的是鲍勃的照片
推荐答案
我已经编辑了我的答案以反映您的额外评论.
I've edited my answer to reflect your extra comments.
首先,您不应该需要 :joins
参数;<代码>:include =>:photos 应该为你处理幕后"的加入.
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.
(在模型中)
class Profile < ActiveRecord::Base
has_many :photos
has_one :primary_photo, :class_name => "Photo", :conditions => {:primary => true}
end
(在控制器中)
@profiles = Profile.find(:all, :include => :primary_photo)
(在视图中)
<% @profiles.each do |profile| %>
Name: <%= profile.name %>
Age: <%= profile.age %>
Photo: <%= image_tag profile.primary_photo.url %>
<% end %>
这篇关于Ruby on Rails:如何连接两个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!