Skip to content

Instantly share code, notes, and snippets.

@glennfu
Last active March 25, 2020 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glennfu/b9cd530973b2f8a422c174986280b7a2 to your computer and use it in GitHub Desktop.
Save glennfu/b9cd530973b2f8a422c174986280b7a2 to your computer and use it in GitHub Desktop.
# The models
class TextMessage < ApplicationRecord
belongs_to :account, inverse_of: :text_messages, optional: true
belongs_to :user, inverse_of: :text_messages, optional: true
has_many :phones, ->(text_message) { joins(name: :products).where("products.account_id = ?", text_message.account_id) }, foreign_key: :number, primary_key: :client_phone_number
has_many :names, through: :phones, source: :name
class Phone < ApplicationRecord
belongs_to :name, inverse_of: :phones
has_many :text_messages, ->(phone) { phone ? where("text_messages.account_id = ?", phone.name.products.first&.account_id) : nil }, foreign_key: :client_phone_number, primary_key: :number
class Product < ApplicationRecord
belongs_to :name, inverse_of: :products
has_many :phones, through: :name
has_many :text_messages, through: :phones, foreign_key: :client_phone_number, primary_key: :number
has_many :unread_texts, -> { unread }, through: :phones, foreign_key: :client_phone_number, primary_key: :number, class_name: "TextMessage", source: :text_messages
# This Works
ph = Phone.where(number: "3368483334").joins(name: :products).where("products.account_id = ?", 16).last
ph.text_messages
=> looks good
product = ph.name.products.first
product.text_messages
=> looks good
product.text_messages.unread.size
=> 79
product.unread_texts.size
=> 79 # still good
product_again = Product.eager_load(:unread_texts).where(id: product.id).first
product_again.unread_texts.size
=> 82 # grabs 3 text extra text messages because they're not scoped by account_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment