我有Bank
和Rating
个型号。银行有很多评级。此外,银行可以是活动的和非活动的(当许可证被暂停时)。
当许可证被暂停时,非活动银行在数据库中具有日期字段(license_suspended
)。活跃银行在此领域有nil
。
我只需要查找有效银行的评级。我可以找到license_suspended: nil
的所有银行,然后找到与当前日期相关的评级,并逐个添加到数组,但我认为有更好的方法。我需要这样的东西:
@ratings = Rating.where(date: Date.today.beginning_of_month, bank: bank.license_suspended.blank?)
谢谢!
答案 0 :(得分:1)
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
答案 1 :(得分:0)
假设评级属于银行,看起来它会做你想做的事情:
Rating.joins(:bank).where(date: Date.today.beginning_of_month, bank: {license_suspended: nil}