0

I'm new to the Ruby on Rails environment, so I am stuck on what might be a simple question: I'm looking to define some text strings/labels that correspond to a numeric value. These values will be stored in the database and then used in my code instead of the numeric values.

In C, I would to something like this:

    #define Accounting  0
    #define Engineering 1
    #define Education   2

...to be used like this:

    if (field_of_study == Accounting) ...

I want to be able to do this in Rails controllers/views. I currently have to do something like this in my views to display items:

    <tr>
      <td><%= link_to user.name, user %></td>
      <% if user.studyField == 0 %>
        <td>Accounting</td>
      <% elsif user.studyField == 1 %>
        <td>Engineering</td>
      <% elsif user.studyField == 2 %>
        <td>Education</td>
      <% end %>
    </tr>

I would also like to use the text strings/labels in a drop-down menu in the form_for form and then save it using the numeric identifier. Do I need a before_save method to translate the two or is their an automatic way of doing this?

4444
  • 3,541
  • 10
  • 32
  • 43
Robert Reynolds
  • 127
  • 2
  • 9
  • If I understand correctly, you could set up an Enumerable to do this. – 4444 Aug 02 '13 at 19:29
  • I completely understand how coming from a C environment, this would be your approach, but it's very un-ruby like. In ruby, you are more likely to use symbols like `:accounting :engineering :education` – Daiku Aug 02 '13 at 20:08
  • Robert Reynolds - did one of the answers help you or do you have additional questions? If one of the answers meets your needs, can you please mark it as correct? Thanks. – Powers Aug 04 '13 at 18:53

2 Answers2

1

You might find this helpful: Ruby on Rails: Where to define global constants?.

In Rails, since all models are autoloaded by default, you might find it convenient to define your constants in the models, as follows

class User < ActiveRecord::Base
  ACCOUNTING = 0
  ENGINEERING = 1
  EDUCATION = 2
end

or even

class User < ActiveRecord::Base
  FIELDS = { accounting: 0, engineering: 1, education: 2 }
end

These can be used anywhere with User::ACCOUNTING or User::FIELDS[:accounting]. To use the second version inside a form, you can use

select('user', 'study_field', User::FIELDS)

Refer to select for more details.

Community
  • 1
  • 1
James Lim
  • 12,915
  • 4
  • 40
  • 65
0

There are a couple of ways to do this. You can assign the constants to integers and they should be saved to the database as integers:

# config/initializers/constants.rb
Accounting = 0
Engineering = 1

This is a bit ugly because Accounting is literally equal to zero. In Rails console:

Accounting == 0
=> true

However, this is probably the most straightforward way to meet your requirement and it looks like this is how your approached the problem with C.

Powers
  • 18,150
  • 10
  • 103
  • 108