gpt4 book ai didi

ruby-on-rails - 未初始化的常量 Item::Types

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:17 25 4
gpt4 key购买 nike

提交嵌套表单时出现未初始化常量错误。

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

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

最佳答案

您需要特别注意 Rails 中的多元化。在这种情况下,您正在建立与复数事物的单数关系,因此假定您实际上是在调用名为“Types”而不是“Type”的类。

  • 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

关于ruby-on-rails - 未初始化的常量 Item::Types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2503007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com