Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access model-specific constants in a Rails view

I'm running Rails 4.

I have a model called Challenge, and in my database I'm storing the status of each challenge in terms of 0-4.

But 0-4 isn't very semantic so I want to define a few variables (I'm assuming a constants) so that in any controller or view I can access the number by calling the constant:

# Challenge.rb class Challenge < ActiveRecord::Base   SUGGESTED = 0   APPROVED = 1   OPEN = 2   VOTING = 3   CLOSED = 4 end 

I want to access these in my view:

# challenge/_details.html.erb <% if @challenge.status == CLOSED %>   Challenge is closed, broheim! <% end %> 

But my view doesn't want to render.

uninitialized constant ActionView::CompiledTemplates::CLOSED 

What's the best way to set my status variables so that they may be accessed everywhere I need them? (i.e, anywhere the @challenge variable is present)

like image 705
alt Avatar asked Jul 04 '13 19:07

alt


1 Answers

You should access them as following:

Challenge::CLOSED 

Since your CLOSED constant is defined within a class, you need to access the constant using the scope resolution operator. So if your view you would check it like:

# challenge/_details.html.erb <% if @challenge.status == Challenge::CLOSED %>   Challenge is closed, broheim! <% end %> 
like image 183
vee Avatar answered Oct 10 '22 23:10

vee