Scope of Class variables

I have an ActiveRecord class called User where I created a class
variable (hash) called Languages:

def User.languages
{“J” => “Java”, “P” => “Python” , “R” => “Ruby”, “C” =>“C#”, “A”
=>“Any”}
end

Anytime I wanted to resolve a language to the human readable equivalent,
I would simply (in the view), call

<%=User.languages["#{variable}"]%>

Well, I started work on a new view (rhtml) inside a completely different
controller than I was using before with no references or connection
whatsoever to the User class. So when I attempted the above ‘lookup’ of
a language, I received:

“uninitialized constant User”.

Is there a way to make a particular ActiveRecord class ‘visible’ in a
view?

Can I just create a different Class (not an ActiveRecord) and make it
‘visible’ to an arbitrary view?

def User.languages
{“J” => “Java”, “P” => “Python” , “R” => “Ruby”, “C” =>“C#”, “A”
=>“Any”}
end

Can I just create a different Class (not an ActiveRecord) and make it
‘visible’ to an arbitrary view?

In this case you could create a helper in your application helper file
that all views could access, since the languages aren’t really tied to
the user model from a db perspective.

Then you could pass the helper the variable and have it return the
appropriate result.

David C. wrote:

In this case you could create a helper in your application helper file
that all views could access, since the languages aren’t really tied to
the user model from a db perspective.

Then you could pass the helper the variable and have it return the
appropriate result.

duh. thanks.

On a side note, it was a complete pain to try to figure out how to use
that hash in a select box withinin a view. Most existing helpers seem
to be designed to use an array or a collection of objects with exposed
methods to access value/description.

I ended up with the slightly hackish (but I thought really neat):

<%= collection_select(‘user’,‘language’, languages, “first”, “last”)%>

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs