0

I have a static array in my User model declared like this:

class User < ActiveRecord::Base
...
states = ['NYC', 'CAL', ...]
...
end

I know I should create a model for the states but I figured I just need the list for registration purposes. When I try to use it in a view like this:

= f.select(:state, options_for_select(states))

I get a Undefinded Method error. I tried using instance variables through the controller and that didnt work either. Whats the correct way of doing this?

1
  • use STATES = ['NYC', 'CAL', ...] in corresponding controller, instead of model Commented Aug 15, 2014 at 15:31

2 Answers 2

1

You should be able to access it as

User::STATES

that's assuming you upcase it from states to STATES since that's idiomatic :)

Another option is to create a class method that returns the array

def self.states
  ['NYC', 'CAL', etc]
end

Capitalizing the constant in the model and using the Model::CONSTANT syntax is probably the most common way to do this.

Sign up to request clarification or add additional context in comments.

2 Comments

That made the trick thank you. Is declaring User::STATES inside the view the Rails way of doing this tho?
The model is where you want to define it IF it belongs with the model. You can also do things like have application constants in a non-model lib/ or concerns/ directory.
0

States collection is not specific to a user, so I wouldn't have it under the User model. As shown in this answer, I would add a us_states helper to your application, and use that in your views:

= f.select(:state, options_for_select(us_states))

2 Comments

Thank you this seems more appropriate.
Yep -- a helper handles it better here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.