Best way to return data entered by a select of constants

1

I have a Usuario template and for it I have two constants that define a type for it. To pass this information to a select I have a type method that returns a Array . Ex:

#models/Usuario.rb
class Usuario < ActiveRecord::Base
    def tipos
        [["Tipo 1",1], ["Tipo 2",2]]
    end
end

#views/usuarios/_form.html.erb
        <div class="field">
            <%= f.label :tipo %><br>
            <%= f.select :tipo,@usuario.tipos, :class=>"form-control" %>
        </div>

So, in my index will appear 1 and 2 respectively to their types. Obviously I would like Type 1 and Type 2 to be displayed in each case .

Currently as I'm doing this:

#models/Usuario.rb
class Usuario < ActiveRecord::Base
    def tipos
        [["Tipo 1",1], ["Tipo 2",2]]
    end

    def tipo_tos
        #inverte chave, valor, converte em Hash, pega o nome do tipo
        Hash[tipos.map { |t| [t[1],t[0]]  }][self.tipo]
    end

end

Some more efficient way to do this?

    
asked by anonymous 13.03.2014 / 15:48

1 answer

3

Instead of turning the list into a hash you can do the search directly using the find method. So:

def tipo_tos
    tipos.find {|t| t[1] == tipo}[0]
end

But perhaps the most interesting thing is to save the types as a hash from the beginning. So:

class Usuario < ActiveRecord::Base
    TABELA_TIPOS = {
        1 => "Tipo 1",
        2 => "Tipo 2"
    }
    TIPOS = TABELA_TIPOS.to_a.map(&:reverse)

    def self.tipos
        TIPOS
    end

    def tipo_tos
        TABELA_TIPOS[tipo] # Eficiente!
    end
end

With this you can call Usuario.tipos to get the list (I made it to a class method, since it does not use the instance).

    
13.03.2014 / 15:57