Best way to return data entered by a select of constants

Asked

Viewed 227 times

1

I have a model Usuario and for him I have two constants that define a type for him. To pass this information to a select I have a method types 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 mine index will be displayed 1 and 2 respectively to their types. Obviously would like Type 1 and Type 2 to be displayed in each case.

Currently as I’m doing so:

#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?

1 answer

3


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

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

But perhaps the most interesting thing is to store 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 that you can call Usuario.tipos to get the list (turned into a class method, since it does not use the instance).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.