Home > Enterprise >  Rails scope with associations
Rails scope with associations

Time:09-25

So currently I have this scope:

  scope :ending_documents, -> { where('document1_valid_to <= ? OR document2_valid_to <= ? OR document3_valid_to <= ? OR document_4_valid_to <= ? ', Time.zone.now.end_of_day   30.days, Time.zone.now.end_of_day   30.days, Time.zone.now.end_of_day   30.days, Time.zone.now.end_of_day   30.days ) }

I'm using this scope to find users who have at least 1 document that ends in 30 days or has ended. But I need to find another document through associations.

class User 
  has_many :user_cards

class UsersCard
  belongs_to :user
  belongs_to :card

class Card
  belongs_to :user
  has_many :user_cards

These are the example tables.

How can I also add ending cards assigned to the user in same scope? I red about joins but how can I do it when the association goes through like that? Thanks in advance!

CodePudding user response:

I suggest you to use has_many :through association

class User 
  has_many :user_cards, dependent: :destroy
  has_many :cards, through: :user_cards

  scope :ending_documents, -> { joins(user_cards: :cards).where('users.document1_valid_to <= ? OR users.document2_valid_to <= ? OR users.document3_valid_to <= ? OR users.document_4_valid_to <= ? OR cards.valid_to <= ?', Time.zone.now.end_of_day   30.days, Time.zone.now.end_of_day   30.days, Time.zone.now.end_of_day   30.days, Time.zone.now.end_of_day   30.days, Time.zone.now.end_of_day   30.days) }
end
  • Related