Read more

Scope to records with a given state in state_machine

Henning Koch
September 07, 2010Software engineer at makandra GmbH

The state_machine gem ships with a scope with_state. This scope has some problems in complex queries or scope chains.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Use this instead:

named_scope :having_state, lambda { |*state_or_states|
  state_or_states = Array.wrap(state_or_states).map(&:to_s)
  { :conditions => [ 'articles.state IN (?)', state_or_states ] }
}

If you want a scope with hash options (with the side effects you should know about):

named_scope :having_state, lambda { |*state_or_states|
  state_or_states = Array.wrap(state_or_states).map(&:to_s)
  state_or_states = state_or_states.first if state_or_states.size == 1
  { :conditions => { :state => state_or_states } }
}
Posted by Henning Koch to makandra dev (2010-09-07 11:24)