Ruby on rails 关于使用表格_的澄清
创建搜索表单时,我面临一个问题。我得到以下错误:Ruby on rails 关于使用表格_的澄清,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,创建搜索表单时,我面临一个问题。我得到以下错误: undefined method `model_name' for NilClass:Class 这是我的视图文件: “日期选择器”%> 这是我的客户_controller.rb: class ClientsController < ApplicationController def newClients end end 一旦我点击提交按钮,它就会显示错误为 No route matches [GET] "/search" 首
undefined method `model_name' for NilClass:Class
这是我的视图文件:
“日期选择器”%>
这是我的客户_controller.rb:
class ClientsController < ApplicationController
def newClients
end
end
一旦我点击提交按钮,它就会显示错误为
No route matches [GET] "/search"
首先,在控制器中,请遵循Rails命名约定。方法名称应为
new\u clients
或new
def new
@client = Client.new
end
视图名称应为new.html.erb
您没有在控制器中定义
@client
,而是在使用它的视图中定义。您在这里缺少了一些东西。让我解释一下
在控制器中,您不需要定义自定义方法(称为newClients
),因为Rails惯例建议使用以下方法:
class ClientsController < ApplicationController
# GET /clients
def index
@clients = Client.all
end
# GET /clients/:id
def show
@client = Client.find(params[:id])
end
# GET /clients/new
def new
@client = Client.new
end
# POST /clients
def create
@client = Client.new(params[:client])
if @client.save
redirect_to :back, success: "Successfully created..."
else
render :new
end
end
# GET /clients/:id/edit
def edit
@client = Client.find(params[:id])
end
# PUT /clients/:id
def update
@client = Client.find(params[:id])
if @client.update_attributes(params[:client])
redirect_to :back, success: "Successfully edited..."
else
render :edit
end
end
# DELETE /clients/:id
def destroy
@client = Client.find(params[:id]).destroy
redirect_to :back, success: "Successfully deleted..."
end
end
其中
@client
是client.new
在您的情况下。def newClients@client=client.new end
在您的控制器中,您没有定义@client,但鉴于您正在使用它……还有一件事请遵循rails命名约定,方法名称应该是new\u clients
或'new`我如何为searchIf执行此操作我提供出生数据并提交表单。它应该列出所有具有相同出生数据的用户。然后在controllerdef search@results=User中添加一个方法。其中('created_at=?',params[:bithday]。to_datetime)end
Ok我将在controller中添加一个方法作为搜索,但在我的表单中如何提及它?forRails没有提供这些方法。只有当你使用脚手架的时候,它才会这样做,但在这个问题上并没有这种迹象。此外,他想搜索,而不是创建、更新或删除。是的,但他不做创建、更新或删除。唯一相关的可能是索引
。但是,在控制器中创建自己的方法并不是犯罪。这是消除错误的解决方案,但它并不能回答我的问题。问题是为什么和如何。“为什么”部分完全缺失。
def new
@client = Client.new
end
class ClientsController < ApplicationController
# GET /clients
def index
@clients = Client.all
end
# GET /clients/:id
def show
@client = Client.find(params[:id])
end
# GET /clients/new
def new
@client = Client.new
end
# POST /clients
def create
@client = Client.new(params[:client])
if @client.save
redirect_to :back, success: "Successfully created..."
else
render :new
end
end
# GET /clients/:id/edit
def edit
@client = Client.find(params[:id])
end
# PUT /clients/:id
def update
@client = Client.find(params[:id])
if @client.update_attributes(params[:client])
redirect_to :back, success: "Successfully edited..."
else
render :edit
end
end
# DELETE /clients/:id
def destroy
@client = Client.find(params[:id]).destroy
redirect_to :back, success: "Successfully deleted..."
end
end
form_for @client