Scope to records with a given state in state_machine

Updated . Posted . Visible to the public.

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

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 } }
}
Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-09-07 09:24)