我很难看到我在这里做错了什么..
我有一个订单模型,需要能够容纳一个产品,产品需要是多态的。
我有一个名为orthosis_specification的产品/型号,出于某种原因,当我在fields_for创建中使用它时,我收到此错误。
迁移 -
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.datetime :order_date
t.datetime :date_required
t.boolean :correct
t.references :user, index: true, foreign_key: true
t.references :practitioner, index: true, foreign_key: true
t.references :product, polymorphic: true
t.references :shipping_address, index: true, foreign_key: true
t.references :invoice_address, index: true, foreign_key: true
t.timestamps null: false
end
end
end
订单控制器 -
def new
@order = Order.new
@order.build_patient
@order.build_product #Also tried: @order.build_orthosis_specification
end
订单型号 -
class Order < ActiveRecord::Base
has_one :patient
belongs_to :product, polymorphic: true
accepts_nested_attributes_for :patient,
reject_if: proc { |attributes| attributes['first_name'].blank? },
allow_destroy: true
accepts_nested_attributes_for :product,
reject_if: proc { |attributes| attributes['transfer_name'].blank? },
allow_destroy: true
def to_s
name
end
end
矫形器规格模型 -
class OrthosisSpecification < ActiveRecord::Base
has_one :order, :as => :product, class_name: 'Order'
end
订单查看 -
<%= form_for(@order) do |f| %>
<% if @order.errors.any? %>
<% end %>
<%= f.fields_for :orthosis_specification do |fa| %>
实际错误讯息 -
undefined method `build_orthosis_specification' for #<Order:0x007f8950e29970>
矫形器规格迁移 -
class CreateOrthosisSpecifications < ActiveRecord::Migration
def change
create_table :orthosis_specifications do |t|
t.string :transfer_name
t.string :modifications
t.string :primary_mods
t.string :top_opening
t.string :side_opening
t.string :chape_position
t.string :scan_file
end
end
end
非常感谢任何帮助,谢谢!
答案 0 :(得分:1)
多态关联不会生成build_xxx方法。只有在您知道要创建的产品类型时,才能创建新产品:
#Creating a new OrthosisSpecification product associated with @order :
@order.product = OrthosisSpecification.new
文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html