Currently, I have an action in my customers controller generating an array of names, @username_array, of all objects of class User with which to populate a drop down menu in a form that creates a new object of class Customer. The form element looks like this right now:
<%= f.select :user_id, @username_array %>
What I’d really like is for the id of the user to be sent into params[:customer][:user_id] instead of the name of that user that is chosen in the drop down. So in my create action in my customers controller I have the following code:
@customer = Customer.new(params[:customer])
@user = User.find_by_name(params[:customer][:user_id]) # where :user_id is actually currently the name selected from the drop down
@customer.user_id = @user.id
Is there an easier way of doing this?
Change your @username_array to include both the name and the id of the user:
Instead of:
Make it:
This could be accomplished by something like this:
Then, f.select will display the name in the dropdown, but the actual value passed in through params[:customer][:user_id] will be the id of the user, which is what you want. With this in place, the following is all you need in the controller action code:
You won’t have to look up the user by name, the params hash will already have the correct id value.
Note that instead of making @username_array an instance variable you could just create a utility method in the helper for this controller, or the application helper:
Then, in your view:
If you put this in your application helper, you can use it everywhere and only have the code in one place (DRY).