return 集合的方法 - Ruby

Method to return a collection - Ruby

说,我有一个名为 posted_listings 的方法,它应该 运行 ActiveRecord 查询和 return User.listings 的集合,其中 posted: true ,其中 posted?Listing class 方法 。到目前为止我一直在做:

class Bar < ActiveRecord::Base
  def posted_listings
    posted_listings = []
    listings.each { |listing| posted_listings << listing if listing.posted? }
    posted_listing
  end
end

但是每次这个查询 运行s 我开始对我的技能(或缺乏技能)感到非常糟糕。 return 发布列表的集合的最有效方法是什么?

编辑:

posted? 不是一个属性,它是一个 class 方法:

class Listing < ActiveRecord::Base
 def posted?
    true if quantity >= 1 && has_sellers? 
  end
end 

def has_sellers?
  sellers.count >=1 #association to Seller
end

你的问题我不是很清楚

你可以试试:

User.listings.where(posted: true)

获取所有用户发布的列表。

或者说 @user 是一个 User 实例:

@user.listings.where(posted: true)

获取特定用户发布的列表。

我建议像这样向您的 Listing 模型添加范围:

scope :posted, -> { where(posted: true) }

然后您可以像这样获取所有已发布的列表:

@user.listings.posted

如果您有兴趣,可以了解有关作用域的更多信息here

更新

试试这个范围:

def self.posted
  joins(:sellers)
    .where('posted = ? AND quantity > ?', true, 0)
    .group('listings.id')
    .having('COUNT(sellers.id) > ?', 0)
end