Cesar Cesar - 6 months ago 30
Ruby Question

How to add a scope for multiple enums in rails

I have a select that displays all enums of an object:

<%= f.select( :state_user
, User.states.keys.map {|state| [state.titleize,state] }) %>


How can I create an scope that allows me to select multiple states?

For example I want to filter all users that are either inactive or suspended.

Thanks

Answer

I got it working with this scope:

 scope :state, lambda { |enum_ids|
  return nil  if enum_ids.empty?
    objArray = []
    enum_ids.each do |key|
      if (User.estados[key])
        objArray << User.estados[key] 
      end
    end
    return nil  if objArray.empty?
    where (["account.state in (?)" ,  objArray])
 }
Comments