Skip to content
Andrew Geweke edited this page Nov 4, 2013 · 4 revisions

Querying is perhaps the simplest aspect of low_card_tables. In short: ignore the fact that there's a low-card table there — almost everything you can do will 'just work', assuming you're using ActiveRecord.

For example, the following all works, exactly as you'd expect:

# Querying
# (these methods automatically generate queries like WHERE user_status_id IN (2, 4, ...))
User.where(:deleted => true)                           # simple queries
User.where(:deleted => true).where(:deceased => true)  # chained queries

User.where(:status => { :deleted => true, :deceased => true }) # explicitly name the low-card association
User.where(:status => { :deleted => true }).where(:status => { :deceased => true }) # correctly chains; you'll get back just rows that match both conditions

class User < ActiveRecord::Base
  # default scopes
  default_scope { where(:deleted => false) }
  
  # named scopes
  scope :undead { where(:deleted => false, :deceased => true) }
  
  # class-method scopes
  def self.unpaid_men
    where(:gender => 'male').where(:payment_status => 'none')
  end
end

The keys you use in your query are the delegated method names (see Delegation for more information), so, if you use :prefix, use the prefixed name. If you restrict the set of delegated methods using :delegate, or have method-name collisions, simply use the long form where you explicitly call out the low-card association:

# All non-deleted users who haven't deleted their profile image, either
User.where(:status => { :deleted => false }).where(:profile_image_status => { :deleted => false })

About the only thing you have to be careful of is text-based queries, whether that's find_by_sql or just where("<some textual SQL>"). For these, you need to change the queries:

  • If possible, change them to normal ActiveRecord syntax: where(:deleted => false, :deceased => false).
  • If not possible, you'll need to constrain directly: where("user_status_id IN (:ids)", :ids => UserStatus.low_card_ids_matching(:deleted => false, :deceased => false).
Clone this wiki locally