0

While creating a search form I am facing a problem. I am getting the following error:

undefined method `model_name' for NilClass:Class

This is my view file:

"datepicker" %>

This is my clients_controller.rb:

class ClientsController < ApplicationController
  def newClients
  end
end

And this is my model client.rb:

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

I am confused in using form_for parameter. Can any one explain it briefly how and why to use form_for parameter?

Edit 1

I have modified my controller as

class ClientsController < ApplicationController
  def search
      redirect_to root_path
  end
end

Once i click submit button it showing error as

No route matches [GET] "/search"
4

2 回答 2

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

@client你的情况在哪里Client.new

于 2013-08-28T10:02:01.890 回答
0

首先,在您的控制器中,请遵循 Rails 命名约定。方法名称应该是new_clientsor new

def new
  @client = Client.new
end

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

您不是@client在控制器中定义,而是在您正在使用它的视图中定义。

于 2013-08-28T09:59:34.380 回答