Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I join two values in a select form?

In my users model I have a first_name and a last_name and I'm wondering what the best way to go about joining the two of them in a select form would be. Essentially I want to be able to have the following code in one of my forms <%= f.collection_select :user, @users, :id, :fullname, include_blank: 'none' %> Is there a way to do this without creating a fullname field in my migration and having to assign it when the model created/updated?

I should also mention that this is a rails 4 project. Any help would be appreciated, thanks.

like image 500
Tyler Morgan Avatar asked Nov 28 '25 17:11

Tyler Morgan


1 Answers

You can create the method full_name on the User model. It will return the first_name + last_name of the user:

# user model
def full_name
  "#{first_name} #{last_name}"
end

# with a collection_select, in your case:
<%= f.collection_select :user, @users, :id, :full_name, include_blank: 'none' %>
like image 185
MrYoshiji Avatar answered Dec 01 '25 09:12

MrYoshiji