【问题标题】:Method to return a collection - Ruby返回集合的方法 - Ruby
【发布时间】: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


    【解决方案1】:

    我建议像这样向您的 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
    

    【讨论】:

    • 我的问题是posted?是一个类方法,而不是一个属性。
    • 您能否列出您的posted? 方法的完整来源?仍然可以使用范围,但我需要先查看该代码。
    • 是的!最终在.where 中使用了原始 SQL。
    • 很高兴你能成功!只需说明您原来的posted_listings 方法,它可以简化为listings.select(&amp;:posted?)。 Ruby 有很多简洁的方法可以让你进行这样的简化,所以我想你可能会感兴趣。我建议查看一些核心类的文档,例如StringArrayHash,以了解它们。这样做对我学习 ruby​​ 有很大帮助!
    【解决方案2】:

    你的问题对我来说不是很清楚。

    你可以试试:

    User.listings.where(posted: true)

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

    或者,说@user是一个用户实例:

    @user.listings.where(posted: true)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      相关资源
      最近更新 更多