Case Statement

Hi!

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?

Thanks...

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

and then in the view call:

<h2> Priority: <%= @my_model_instance.priority %> </h2>

Allan

How about a Helper?

Thank you for the information. I'm currently trying to look at what a helper is and how to implement it. :slight_smile: 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!

Thanks again for the fast response!

I would map the numbers in the model:

class MyModel

  PRIORITIES = {     1 => 'Low',     2 => 'Medium',     3 => 'High'   }

end

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.

Oh my god....that really worked! Thank you so very much!!!!!!

As I said, I'm just starting out with RoR and I guess I'm just surprised that it worked without many problems!

Thank you again so much!!!!

Mike

wiz561 wrote:

Oh my god....that really worked! Thank you so very much!!!!!!

def priority_name

    return {1=>"Low",2=>"Medium",3=>High}.fetch(priority, "Oops")

end

Sometimes one kind of statement works better and sometimes another works better.

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.

Google "Don't Repeat Yourself". It's a deceptively simple concept that motivates all of software design.