下拉选择器,选定的选项
我正在使用 Ruby on Rails 版本 3。我为选择器定义了以下辅助方法:
def current_user_selector
collection_select(:user, :id, User.all, :id, :name, {:prompt => "Select a User"});
end
我在 index.html.erb
中引入了上述选择器:
...
<%= current_user_selector %>
...
我在某处读到所选选项可以通过以下方式在控制器中访问下拉菜单:
selected_user = params[user][id]
我已在控制器的多个操作中添加了上述行,但我不断收到异常。
目前我有以下操作:
# 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
我的问题是,如何获取下拉菜单的选定用户。
纳伦·西索迪亚(Naren Sisodiya)让我发现了以下例外:
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.[]
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 is, 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.[]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
params[:user][:id] 将为您提供所选用户的 id,因此您需要找到使用此 id 的用户。
编辑:
还要确保您以 params[:user][:id] 的形式访问它,而不是 params[user][id]
更新:
您需要传递所选内容值到服务器,正如您提到的,您有一个调用单击操作的按钮。现在您可以创建一个带有下拉菜单和一个提交按钮的表单;某事作为
params[:user][:id] will give you id of selected user, so you need to find the user using this 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