【问题标题】:How to get records where associated's associated_id is a given value如何获取关联的关联 ID 是给定值的记录
【发布时间】:2019-10-09 08:53:44
【问题描述】:

我有一个属于一个城市的郊区活动记录并且有很多列表,我想获取郊区城市为给定值的列表。

    listings = Listing.joins(:suburbs).where('listings.updated_at >= ?', 2.months.ago).where('city_id = ?', city_id)

【问题讨论】:

  • 我已经用更多信息更新了答案。请检查一下。

标签: sql ruby-on-rails postgresql


【解决方案1】:

我假设您已经定义了这些关联。如果我错了,请纠正我。

郊区班:

has_many :listings
belongs_to :city

在列表类中:

belongs_to :suburb

在城市类中:

has_many :suburbs

现在要获取城市为city_id 的所有列表,您需要将列表与郊区连接,然后与城市连接,然后您需要过滤掉结果。浏览此link 以更好地了解

listings = Listing.joins(suburb: :city).where('listings.updated_at >= ?', 2.months.ago).where(cities: {id: city_id })

这应该可行。

【讨论】:

    【解决方案2】:
    1. 根据给定的 ID 查找郊区
    2. 查找该郊区的所有相关列表。检查docs 了解更多信息。
    Suburb.find(city_id).listings.where('updated_at >= ?', 2.months.ago)
    

    【讨论】:

    • 我想要该城市所有郊区的列表,这只会返回一个郊区。但我会通过文档谢谢。
    • 这个问题很少。首先,一个城市可能有很多郊区。其次,find(city_id) 将寻找带有 id: city_id 的郊区,这是错误的。应该是find_by(city_id: city_id)
    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多