我正在研究Rails 3.2.6应用程序。我有Status
模型,Event
模型和Photo
模型。
事件
Has_many :statuses
状态
Belongs_to :event
Has_one :photo
照片
Belongs_to :status
我想获取属于所选事件的所有状态消息(这样可以正常工作)但是 我还想获取属于每个状态消息的照片。我怎么能这样做?
这是我获取属于某个事件的状态消息的方式:
@event = Event.find_by_id (params[:event_id])
@event.statuses
如何在输出中为每条状态消息获取相关照片? 我已经开始了,我想我应该做这样的事情?但那只会得到 照片并没有将它们与各自的状态信息“合并”。
@photos = @event.statuses.collect {|status| status.photo}
答案 0 :(得分:5)
如果您想减少查询,可以执行以下操作
@statuses = Status.where(:event_id=>params[:event_id]).includes(:photo).all
然后您将能够像这样访问
@statuses.each do |status|
status.event_id # access the status
status.photo # access the photo
# status.nil? will check whether photo is there or not
end
答案 1 :(得分:3)
您可以尝试在一个查询中选择所有内容:
@event = Event.where(:id => params[:event_id]).includes(:statuses => :photo).first
请注意,如果没有链式first
,它将返回ActiveRecord::Relation
的实例,而不是Event
模型实例。然后就可以了
@photos = @event.statuses.map(&:photo).compact
修改强>
确定已注意到您对某些没有照片的状态的评论。 IIRC(我现在无法检查这一点),includes
将进行LEFT JOIN(可能取决于底层数据库适配器),返回带有和不带照片的状态,所以你必须要么nil-check个人status.photo
参考或使用compact
过滤掉@photos
中的零个对象,就像我上面所做的那样,具体取决于您的目的。