未初始化的常量Item :: Types

时间:2010-03-23 19:34:28

标签: ruby-on-rails ruby

当我提交嵌套表单时,我得到了这个未初始化的常量错误。

order.rb

class Order < ActiveRecord::Base
  has_many :items, :dependent => :destroy
  has_many :types, :through => :items

  accepts_nested_attributes_for :items
  accepts_nested_attributes_for :types

  validates_associated :items
  validates_associated :types
end

item.rb的

class Item < ActiveRecord::Base
  has_one :types
  belongs_to :order

  accepts_nested_attributes_for :types

  validates_associated :types
end

type.rb

class Type < ActiveRecord::Base
  belongs_to :items
  belongs_to :orders
end

new.erb.html

<% form_for @order do |f| %>
  <%= f.error_messages %>

  <% f.fields_for :items do |builder| %>
    <table border="0">
      <th>Type</th>
      <th>Amount</th>
      <th>Text</th>
      <th>Price</th>
      <tr>
      <% f.fields_for :type do |m| %>
        <td> <%= m.collection_select  :type, Type.find(:all, :order => "created_at DESC"), :id, :name, {:prompt   => "Select a Type" }, {:id => "selector", :onchange => "type_change(this)"} %> </td>
      <% end %>
        <td> <%= f.text_field :amount, :id => "amountField", :onchange => "change_total_price()" %> </td>
        <td> <%= f.text_field :text, :id => "textField" %> </td>
        <td> <%= f.text_field :price, :class => "priceField", :onChange => "change_total_price()" %> </td>
        <td> <%= link_to_remove_fields "Remove Item", f %> </td>
      </tr>
    </table>
  <% end %>
  <p><%= link_to_add_fields "Add Item", f, :items %></p>
  <p>
    <%= f.label :total_price %><br />
    <%= f.text_field :total_price, :class => "priceField", :id => "totalPrice" %>
  </p>
  <p><%= f.submit "Create"%></p>
<% end %>

<%= link_to 'Back', orders_path %>

在orders_controller.rb中创建方法

def create
  @order = Order.new(params[:order])
  respond_to do |format|
    if @order.save
      flash[:notice] = 'Post was successfully created.'
      format.html { redirect_to(@order) }
      format.xml  { render :xml => @order, :status => :created,
                  :location => @order }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @order.errors,
                  :status => :unprocessable_entity }
    end
  end
end

希望你能看到我不能的东西

2 个答案:

答案 0 :(得分:4)

你需要特别注意Rails中的复数化。在这种情况下,你正在建立一个与复数形式的单一关系,所以假设你实际上正在调用一个名为“类型”而不是“类型”的类。

  • has_one,belongs_to是单数
  • has_many是复数

可能的修复:

class Item < ActiveRecord::Base
  has_one :type
  belongs_to :order

  accepts_nested_attributes_for :type

  validates_associated :type
end

class Type < ActiveRecord::Base
  belongs_to :item
  belongs_to :order
end

答案 1 :(得分:1)

在rails中,type是保留字。您必须将模型重命名为其他内容。此外,您必须遵循tadman关于has_one关联的单数名称的说明。

<强>参考

Reserved words in rails