2017-02-18 5 views
0

next_reviewが現在の時刻より前のすべてのカード(ユーザに属している)を見つけたい場合はTime.zone.nowです。以下はRailsで1対1の関連付けを使ってモデルに問い合わせる方法

私はを考えて何

class User < ActiveRecord::Base 
    has_many :cards 
    def next_cards 
    cards.next_cards 
    end 
end 

class Card < ActiveRecord::Base 
    has_one :meta 
    def next_cards 
    # what should I write here? 
    end 
end 

class Meta < ActiveRecord::Base 
    belongs_to :card 
    # what should I write here? 
end 

、対応するモデル内の私のファインダメソッドを維持する必要があり

enter image description here

が行動

を期待し、私のモードであり、

metaモデルの内側(next_repetition <今日)
  1. クエリメタテーブルと、すべてのターゲット・メタ(S)
  2. を取得cardモデル内のターゲットカードを見つけるために、カードの表に(1)の結果を参加
  3. リターンuserモデル

答えて

1
user.cards.joins(:meta).where('metas.next_review_date <= ?', Time.zone.now) 

内部の対象カードの更新

class User < ActiveRecord::Base 
    has_many :cards 
    def next_cards 
    cards.next 
    end 
end 

class Card < ActiveRecord::Base 
    has_one :meta 
    scope :next, -> { joins(:meta).merge(Meta.next) } 
end 

class Meta < ActiveRecord::Base 
    belongs_to :card 
    scope :next, -> { where('next_review_date <= ? ', Time.zone.now) } 
end 

そして

user.next_cards 

代わりの2-、わずか1クエリを実行するreview_date < =今

とメタを有するユーザのみに属するカード、、およびが返されあなたの投稿に示唆した3つの質問。

+0

このクエリは、それが属するモデルに分けることはできますか? –

+0

確かに。実際には、 'scope:next_cards、 - > {joins(:meta).where( 'metas.next_review_date <=?'、Time)のように、この関数をCardスコープ(関数ではなく)に分ける方が良いかもしれません。他のモデルの中では何も変更しないでください。 –

+0

制限を渡す必要がある場合、私は質問を –

関連する問題