LovingRails
LovingRails

Reputation: 1575

Rails4 - How to access constants in a view and display them correctly?

I have constants like following in my user model

app/models/user.rb

GENDER_TYPES = [['Male', false], ['Female', true]]
COUNTRY_TYPES = [["Afghanistan",1],["Aland Islands",2],["Albania",3]..]

In views like user sign up page I access them as follows

  <div>
  <%= f.label :is_female, "Gender" %>
  <%= f.select :is_female,  User::GENDER_TYPES , {}, { :class => 'form-control' } %>
  </div>

  <div>
  <%= f.label :country, "From" %>
  <%= f.select :country,  User::COUNTRY_TYPES , {}, { :class => 'form-control' } %>
  </div>   

This is part of my user model

class AddAdminToUsers < ActiveRecord::Migration
  def change    

    add_column :users, :is_female, :boolean, default: false   
    add_column :users, :country, :integer

  end
end

When a user signs up, I am able to store the data in the table. But when I display a user in views, I am using something like this for gender

  <% if user.is_female %>
    <small>Female</small>
  <% else %>
    <small>Male</small>
  <% end %>

And I don't know how to do it for country. I know there must be better way to do it.

Can someone kindly share how to display user's gender and country which has the above mentioned datastructure?

Upvotes: 1

Views: 88

Answers (2)

keymone
keymone

Reputation: 8104

assuming you're settled with holding your data in constants, here are few tips:

  • use hashes: COUNTRIES = {1 => "Afghanistan"}, you can easily convert that to array of pairs if necessary and you can easily lookup values in both ways:
<% if user.country %>
  <%= User::COUNTRIES[user.country] %>
<% end %>
  • use helpers to present raw data instead of referencing model constants directly, it is also useful when you want to do translations which are part of presentation, not business logic:
def coutries_for_select
  # assuming countries is a hash id => name
  User::COUNTRIES.map {|id, name| [name, id]}
end

Upvotes: 2

Santhosh
Santhosh

Reputation: 29124

May not be perfect, but will do the job

<%= User::COUNTRY_TYPES.map(&:reverse).to_h[user.country] %>

It is better to save the countries in another table, and reference it.

Upvotes: 1

Related Questions