Uninitialized constant Item :: Types

I get this uninitialized persistent error when I submit my sub forms.

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 %> 

create a method in 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 

I hope you see that I can’t

+4
source share
2 answers

You need to pay special attention to pluralization in Rails. In this case, you are creating a singular plural relationship, so it was assumed that you were actually calling a class named β€œTypes”, not β€œType”.

  • has_one, belongs_to are special
  • has_many - plural

Possible fixes:

 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 
+4
source

In rails, type is a reserved word. You must rename your model to something else. You should also follow the tadman instructions for special names for the has_one association.

Link

Reserved words in rails

+1
source

Source: https://habr.com/ru/post/1304924/


All Articles