【发布时间】:2023-03-13 21:32:01
【问题描述】:
说,我有一个名为 posted_listings 的方法,它应该运行 ActiveRecord 查询并返回 User.listings 的集合,其中 posted: true,其中 posted? 是 Listing 类方法。到目前为止我一直在做:
class Bar < ActiveRecord::Base
def posted_listings
posted_listings = []
listings.each { |listing| posted_listings << listing if listing.posted? }
posted_listing
end
end
但每次运行此查询时,我都会开始对自己的技能(或缺乏技能)感到非常糟糕。返回已发布列表的集合最有效的方法是什么?
编辑:
posted? 不是属性,它是一个类方法:
class Listing < ActiveRecord::Base
def posted?
true if quantity >= 1 && has_sellers?
end
end
def has_sellers?
sellers.count >=1 #association to Seller
end
【问题讨论】:
标签: ruby-on-rails ruby methods collections iteration