这是从早期的问题开始的,因为我正在围绕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) %>
没有错误,但也没有过滤掉没有照片的项目。
我尝试了各种其他方法,以及尝试做自定义查找器,为照片编写名称范围,但没有什么是很有意义的。我应该从另一个角度接近这个吗?
答案 0 :(得分:2)