Dropdown selector, selected option
I am using Ruby on Rails version 3. I have defined the following helper method for a selector:
def current_user_selector
collection_select(:user, :id, User.all, :id, :name, {:prompt => "Select a User"});
end
I have introduced the aforementioned selector in my index.html.erb
:
...
<%= current_user_selector %>
...
I've read somewhere that the selected option from the dropdown menu could be accessed in the controller with:
selected_user = params[user][id]
I have added the above line in several actions of my controller but I keep getting exceptions.
Currently I have it in the following action:
# GET /users/:id/click
# GET /users/:id/click.xml
def click
@user = User.find(params[:id])
@users_to_click = User.where("clicks_given - clicks_received >= ?", -5).order("clicks_given - clicks_received")
selected_user = params[user][id]
respond_to do |format|
format.html # click.html.erb
format.xml { render :xml => @user }
end
end
My question i开发者_如何学JAVAs, how and I get the selected user of the dropdown menu.
Naren Sisodiya led me to the following exception:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
params[:user][:id] will give you id of selected user, so you need to find the user using this id.
selected_user = User.find(params[:user][:id])
EDIT:
also make sure that you are accessing it as params[:user][:id] instead params[user][id]
Update:
you need to pass the selected value to server, as you mentioned you have a button that invokes the click action. Now you can create a from with dropdown and one submit button; something as
<%= form_tag('/click',:method=>'get') do -%>
<%= current_user_selector %>
<%= submit_tag 'Get Selected' %>
<% end -%>
精彩评论