测试Ruby on Rails中缺少关联对象

时间:2012-08-18 17:41:19

标签: ruby-on-rails

这是从早期的问题开始的,因为我正在围绕Ruby on Rails弯曲我的大脑。

我有一些显示在网页上的项目,具体取决于他们的状态是否允许显示,使用命名范围 - 如果文档状态(“For Sale”,“Sold”,“Deleted”等)具有show_latest_items标志设置为1,它将允许相关项目显示在页面上:

class Item < ActiveRecord::Base
  belongs_to :status
  scope :show_latest_items, joins(:status).where(:statuses => {:show_latest_items => ["1"]})
end

class Status < ActiveRecord::Base
  has_many :items
end

这是当前显示的方式

<% latest_items = Items.show_latest_items.last(30) %>
<% latest_items.each do |i| %>
  :
<% end %>

所以这一切都很好,但我现在只想显示项目,如果它有相关的照片。

class Item < ActiveRecord::Base
  has_many :item_photos
end

class ItemPhoto < ActiveRecord::Base
  belongs_to :item
end

所以在我看来,我应该使用命名范围,拉回要显示的项目列表,然后使用.present过滤它们?或者.any?方法。奇怪的是这个:

<% latest_items = Items.show_latest_items.where(:item_photos.any?).last(30) %>

返回错误:

undefined method `any?' for :item_photos:Symbol

鉴于:

<% latest_items = Items.show_latest_items.where(:item_photos.present?).last(30) %>

没有错误,但也没有过滤掉没有照片的项目。

我尝试了各种其他方法,以及尝试做自定义查找器,为照片编写名称范围,但没有什么是很有意义的。我应该从另一个角度接近这个吗?

1 个答案:

答案 0 :(得分:2)

:item_photos.any?

这不起作用,因为Ruby的Symbol没有any?方法。

.where(:item_photos.present?)

由于您在符号:item_photos上调用.present?并且评估为true,因此您无法进行过滤,因此条件确实

.where(true)

尝试简单

<% latest_items = Items.show_latest_items.joins(:item_photos).last(30) %>

.joins(:item_photos)的SQL将是INNER JOIN,导致Item个实例没有关联的ItemPhoto个实例从结果中省略。