【发布时间】:2016-05-11 22:51:31
【问题描述】:
我正在使用“GET”方法的表单。我创建了一个文本字段(在 testing.html.erb 中)供用户输入名称。我希望将名称传递给控制器并基于名称,我想通过查询从数据库中检索他的数据。 这里的问题是我没有在控制器操作中的实例变量中输入任何内容(当我在“testing.html.erb”中显示@testing 时,屏幕上没有打印任何内容)。下面是我的 routes.rb 文件。
Rails.application.routes.draw do
resources :users
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
get 'index' => 'users#index'
get 'testing' => 'users#testing'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
.....
这是我的 testing.html.erb 文件
<h1> Testing page </h1>
<%= form_for users_path, :url => {:action => "testing", :name => :name}, :html => {:method => :get} do |f| %>
<%= f.label :first_name %><br />
<%= f.text_field :name %><br />
<%= f.submit "View Schedule" %>
<% end %>
<%= @testing %>
<%#= @testing.email %>
<%#= @testing.content %>
请注意,我在上面的文件中注释了@testing.email/content 以抑制错误(nil:NilClass 的未定义方法`email')。
下面是我的 users_controller.rb 文件。
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
#before_action :user_set, only: [:testing]
# GET /users
# GET /users.json
def index
@users = User.all
@test = params[:name]
@test_index = params[:age]
end
# GET /users/1
# GET /users/1.json
def show
end
def testing
@testing = User.find_by(name: params[:name])
#if @testing.name == "Siri"
# #render text: "Hello #{@testing.name}"
#redirect_to action: :index
#end
end
.........
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:name, :email, :content)
end
end
日志文件显示以下内容。
Processing by UsersController#testing as HTML
Parameters: {"utf8"=>"✓", "/users"=>{"name"=>"hello rails"}, "commit"=>"View Schedule"}
我还尝试将强参数用作 User.find_by(name: params[:users][:name]) ,这会引发错误“undefined method `[]' for nil:NilClass”。
我想我在某个地方出错了。请纠正我。感谢您的宝贵时间。
【问题讨论】:
标签: ruby-on-rails forms