Say I have a form_for with a select menu to assign a User on a belongs_to association:
...
form.select :user_id, @users, :prompt => "Select a User"
...
Currently I have @users in the controller as follows:
@users = User.all.map { |u| [u.full_name, u.id] }
I feel like this logic should maybe moved into a helper or even to the model.
But I am confused as to where to deal with this and how.
The general answer depends on how often you’re going to use it:
However in your case, the answer is none of the above, and stop trying to reinvent the wheel. About 95% of the things people try to do with Rails are tasks that others have already done. There’s a very good chance that it’s either in the Rails Core or exist in either gem or plugin form.
What you’re trying to do has already been done, and is built into the Rails core. It’s a ActionView::Helpers::FormOpitionsHelper method called collection_select
collection_select does exactly what you want to do, it’s also much more robust than a single purpose method.
It has the form of
value_method and text_method are sent to each item in collection to get the select value and the display text for each select option. It is not required that either are column names.
Use it like this: