2012-04-22 67 views
3

我想在用戶創建時保留表單中的值order(所以如果用戶在字段中有錯誤,那麼用戶會得到頁面與他/她已經打印的參數)。所以我接下來做Rails 3 - 未定義方法`model_name'爲NilClass:當我嘗試呈現'新'方法時的類

控制器

class OrdersController < ApplicationController 
    ... 

    def new 
    @everpresent_field_placeholder = "Fill that" 
    @order = Order.new 
    end 

    def create 
    order = Order.new(params[:order]) 

    if order.save 
     flash[:success] = "Yay! Order created!" 
    else 
     render 'new' 
     flash[:error] = order.errors.full_messages.to_sentence :last_word_connector => ", ",   
                  :two_words_connector => ", " 
    end 
    end 
end 

查看新秩序

<legend>Order's creating</legend> 

<%= form_for @order, :html => {:class => "form-horizontal"} do |f| %> 
    <%= field_set_tag do %>  
    <div class="control-group"> 
     <%= f.label :number_of_order, "Number of order", :class => "control-label" %> 

     <div class="controls"> 
     <%= f.text_field :number_of_order, 
         :class => "span2",       
         :placeholder => @everpresent_field_placeholder %> 
     </div> 
    </div> 

    <%= f.submit "Create", :class => "btn btn-large btn-success" %> 
    <% end %> 
<% end %> 

但是,當我在訂單的號碼類型不對勁,然後單擊「創建」我得到這樣的錯誤:

NoMethodError in Orders#create 

Showing .../app/views/orders/new.html.erb where line #3 raised: 

undefined method `model_name' for NilClass:Class 

Extracted source (around line #3): 

1: <legend>Order's creating</legend> 
2: 
3: <%= form_for @order, :html => {:class => "form-horizontal"} do |f| %> 
4: <%= field_set_tag do %>  
5:  <div class="control-group"> 
6:  <%= f.label :number_of_order, "Number of order", :class => "control-label" %> 

我做錯了什麼?

回答

4

調用render 'new'不會調用該控制器方法 - 它只會呈現與該操作關聯的模板。也就是說,您的create操作從未設置@order - 也許如果您在create操作中替換對order@order的引用,則會解決問題。

+0

是的,你是對的!謝謝! – ExiRe 2012-04-22 20:39:37

相關問題