关于使用form_for的说明

时间:2013-08-28 09:42:43

标签: ruby-on-rails ruby-on-rails-3

在创建搜索表单时,我遇到了问题。我收到以下错误:

undefined method `model_name' for NilClass:Class

这是我的观点文件:

           “datepicker”%>            

这是我的clients_controller.rb:

class ClientsController < ApplicationController
  def newClients
  end
end

这是我的模型client.rb:

class Client < ActiveRecord::Base
  # attr_accessible :title, :body
end

我对使用form_for参数感到困惑。任何人都可以简要解释一下使用form_for参数的方法和原因吗?

修改1

我已将我的控制器修改为

class ClientsController < ApplicationController
  def search
      redirect_to root_path
  end
end

点击提交按钮后,显示错误为

No route matches [GET] "/search"

2 个答案:

答案 0 :(得分:2)

你在这里遗漏了一些东西。让我解释一下。

在控制器中,您不需要定义自定义方法(称为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

最后,为了让你的form_for正常工作,你需要传递一个类的实例:

form_for @client

在您的情况下,@clientClient.new

答案 1 :(得分:0)

首先,在您的控制器中,请遵循Rails命名约定。方法名称应为new_clientsnew

def new
  @client = Client.new
end

您的视图名称应为new.html.erb。

您没有在控制器中定义@client,而是在视图中使用它。