Max*_*Max 7 activerecord join ruby-on-rails
我有一个索引页面,我想显示所有用户的个人资料及其相关照片.我正在使用插件Paperclip拍摄照片.在Profiles控制器中,我有实例变量@profile,但它只显示了配置文件表中的表,而不是照片表.
@profile = Profile.find(:all, :include => :photos,
:joins => "INNER JOIN photos ON photos.profile_id = profiles.id")
Run Code Online (Sandbox Code Playgroud)
模型如下所示:
class Profile < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :profile
end
Run Code Online (Sandbox Code Playgroud)
我希望能够在视图中显示的内容如下:
Gre*_*ell 15
我编辑了我的答案以反映您的额外评论.
首先,你不应该需要:joins参数; :include => :photos应该为你处理"幕后"的加入.
这是一种做你要问的方法.
(在模型中)
class Profile < ActiveRecord::Base
has_many :photos
has_one :primary_photo, :class_name => "Photo", :conditions => {:primary => true}
end
Run Code Online (Sandbox Code Playgroud)
(在控制器中)
@profiles = Profile.find(:all, :include => :primary_photo)
Run Code Online (Sandbox Code Playgroud)
(在视图中)
<% @profiles.each do |profile| %>
Name: <%= profile.name %>
Age: <%= profile.age %>
Photo: <%= image_tag profile.primary_photo.url %>
<% end %>
Run Code Online (Sandbox Code Playgroud)