Ruby on Rails:如何连接两个表
我有一个索引页面,我想显示所有用户的个人资料及其相关照片。 我正在使用插件Paperclip来拍照。 在Profiles控制器中,我有实例变量@profile,但它只显示了配置文件表中的表而不是照片表。
@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
我希望能够在视图中显示的内容如下:
- John的个人资料(例如姓名,年龄,性别) – John的照片(例如,只显示了一张照片)
- 玛丽的个人资料 – 玛丽的照片显示在这里
- 鲍勃的个人资料 – 鲍勃的照片显示在这里
我编辑了我的答案以反映您的额外评论。
首先,您不需要:joins
参数; :include => :photos
应该为您处理“幕后”连接。
这是一种做你要问的方法。
(在模型中)
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 %>