3

我想在用户创建订单时保留表单中的值(因此,如果用户在字段中有错误,那么用户将获得带有他/她已经打印的参数的页面)。所以我接下来做

控制器

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

1 回答 1

4

调用render 'new'不会调用该控制器方法——它只会呈现与该操作关联的模板。也就是说,您的create操作永远不会设置@order- 也许如果您在操作中order替换对的引用,那将解决问题。@ordercreate

于 2012-04-22T20:35:04.143 回答