役立つクエリ メソッドを Donor に追加できます。has_many ... through
また、 on DonationCategory を追加すると、特定のカテゴリの寄付に簡単にアクセスでき、次のようにテーブルが自動的に結合されます。
class DonationCategory < ActiveRecord::Base
has_many :donors
has_many :donations, through: :donors
end
class Donation < ActiveRecord::Base
def self.within_dates(start_date, end_date)
where "created_at >= ? AND created_at <= ?", start_date, end_date
end
end
# Query looks like this:
some_category.donations.within_dates(start_date, end_date)
# Or this:
DonorCategory.find(123).donations.within_dates(start_date, end_date)
through
オプションを onで使用するためhas_many
に、データベースを変更する必要はまったくありません。Rails は、寄付、寄付者、およびdonor_categories テーブルを結合することによりdonations
、donor_category からを取得します。donors
あなたはスコープについて言及しました。クラス メソッドはwithin_dates
実質的にスコープです。データベースにクエリを実行するクラス メソッドを作成するための特殊な Rails 構文scope
です。これは冗長なメカニズムですが、DHH は気に入っています。また、同等のクラス メソッドよりもスコープの方が見やすいことが多いことに同意しますが、ここでのようにスコープに引数が必要な場合は、実際にはクラス メソッドの方が簡単だと思います。
アップデート
RFC1337 の回答により、クエリ メソッドを簡略化できることがわかりました。
def self.within_dates(start_date, end_date)
where created_at: start_date..end_date
end