josenova
josenova

Reputation: 5

Rails: Using array from model in a view

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?

Upvotes: 0

Views: 1555

Answers (2)

user419017
user419017

Reputation:

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))

Upvotes: 0

John Paul Ashenfelter
John Paul Ashenfelter

Reputation: 3143

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.

Upvotes: 1

Related Questions