我有我想告诉所有用户的个人资料及其相关的照片索引页。我使用的插件回形针的照片。在情景模式控制器,我有实例变量@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")
的模型如下所示:
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:
在约翰的个人资料(如姓名,年龄,性别) - 约翰的图片(例如,只显示一个图片) 在玛丽的个人资料在这里 - 这里显示玛丽的图片 在Bob的个人资料在这里 - 这里显示鲍勃的图片我已经编辑我的答案,以反映你的额外的意见。
I've edited my answer to reflect your extra comments.
首先,你应该不需要:加入
参数; :包括=&GT; :照片
应处理好加入幕后为您服务。
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
(在控制器)
(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 %>