I am trying to switch from PHP to RoR. In my database, I have an
integer represent a string. So, for example, a row would have a 1, 2,
or 3. For example...
1 = Low
2 = Medium
3 = High
I do not have the Low/Med/High anywhere in the database; I just know
that in a row, 1 is low, 2 is medium, etc... In my view, when I
"show" a record, the record is shown as '1' when I use the
scaffolding.
In PHP, I would just implement a 'case' statement depending on what
the number represents. I was wondering how I would do it in RoR?
Would I use a if statement in the view? Put something in the
controller?
Probably better to put it in the model (untested code :-):
class MyModel < ActiveRecord:base
def priority
case priority_column_name # whatever column you've used to hold the
integer
when 1
return 'High'
when 2
return 'Medium'
when 3
return 'Low'
end
'Unknown priority'
end
Thank you for the information. I'm currently trying to look at what a
helper is and how to implement it. I think that's the correct
route that should be taken now.
However, if I get too frustrated, I'll probably use something like
Allan suggested because I think that would work as well!
In PHP, I would just implement a 'case' statement depending on what
the number represents. I was wondering how I would do it in RoR?
Would I use a if statement in the view? Put something in the
controller?
I would add a method to your model.
Say the db field is "priority" ...
def priority_name
case priority
when 1
"Low"
when 2
"Medium"
when 3
"High"
else
"Oops."
end
end
Then, call @model.priority_name in your view instead of @model.priority.
The advantage of putting it in the model instead of views is that if you add another priority, it's easy to change in 1 place.