簡體   English   中英

查找來自其他模型導軌的條件的記錄

[英]Find records with the condition from other model rails

我有BankRating模型。 銀行有很多評級。 另外,銀行可以是活動的,也可以是非活動的(當許可證被暫停時)。

不活動的銀行在數據庫中具有日期字段( license_suspended )以及許可證被暫停的日期。 活躍的銀行在這一領域幾乎nil

我只需要找到活躍銀行的評級。 我可以找到所有具有license_suspended: nil銀行,然后找到與當前日期相關聯的評級,並將其一對一添加到數組中,但是我認為有更好的方法。 我需要這樣的東西:

@ratings = Rating.where(date: Date.today.beginning_of_month, bank: bank.license_suspended.blank?)

謝謝!

class Bank < ActiveRecord::Base
  has_many :ratings

  scope :active, -> { where(license_suspended: nil) }
end

class Rating < ActiveRecord::Base
  belongs_to :bank
end

我認為這將滿足您的要求:

Rating.joins(:bank).where(date: Date.today).where(bank: {license_suspended: nil})

或這個:

Rating.joins(:bank).where(date: Date.today).merge(Bank.active) //this way you reuse active scope from Bank model

這將導致以下查詢:

SELECT "ratings".* FROM "ratings" INNER JOIN "banks" ON "banks"."id" = "ratings"."bank_id" WHERE "ratings"."date" = 'today_date' AND banks.license_suspended IS NULL

假設評級屬於銀行,這看起來就可以滿足您的要求:

Rating.joins(:bank).where(date: Date.today.beginning_of_month, bank: {license_suspended: nil}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM