我有一个索引页面,我想显示所有用户的个人资料及其相关照片。我正在为照片使用插件 Paperclip。在 Profiles Controller 中,我有实例变量 @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
我希望能够在 View 中显示的内容类似于:
最佳答案
我已经编辑了我的答案以反射(reflect)您的额外评论。
首先,您不需要 :joins
范围; :include => :photos
应该为您处理“幕后”加入。
这是做你问的事情的一种方法。
(在模型中)
class Profile < ActiveRecord::Base
has_many :photos
has_one :primary_photo, :class_name => "Photo", :conditions => {:primary => true}
end
(在 Controller 中)
@profiles = Profile.find(:all, :include => :primary_photo)
(在 View 中)
<% @profiles.each do |profile| %>
Name: <%= profile.name %>
Age: <%= profile.age %>
Photo: <%= image_tag profile.primary_photo.url %>
<% end %>
关于ruby-on-rails - Ruby on Rails : How to join two tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/764538/