How to send user.id with :user in params even though user.name is what is in the form drop down?
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 wa开发者_开发百科y of doing this?
Change your @username_array to include both the name and the id of the user:
Instead of:
["Bob","Sally","Dave"]
Make it:
[["Bob", 1],["Sally",2],["Dave",3]]
This could be accomplished by something like this:
@username_array = User.all.map {|user| [user.name, user.id]}
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:
@customer = Customer.new(params[:customer])
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:
def user_select
User.all.map {|user| [user.name, user.id]}
end
Then, in your view:
<%= f.select :user_id, user_select %>
If you put this in your application helper, you can use it everywhere and only have the code in one place (DRY).
you can do
@user = User.find_by_name(params[:customer][:user_id])
@user.customers.new(params[:customer])
or
@user = User.find_by_name(params[:customer][:user_id])
@customer = @user.customers.create(params[:customer])
but to do that you must have the relation (has_many, belongs_to,...)
or
Customer.new(params[:customer], :user_id => params[:customer][:user_id])
or
f.collection_select :user_id, @username_array, :id, :name
精彩评论