问题描述
我很难看出我在这里做错了什么..
I am struggling to see what I am doing wrong here..
我有一个订单模型,需要能够容纳一个产品,该产品需要是多态的.
I have an order model which needs to be able to hold one product, the product needs to be polymorphic.
我有一个名为 orthosis_specification 的产品/模型,出于某种原因,当我在 fields_for 创建中使用它时出现此错误.
I have a product/model called orthosis_specification and for some reason I am getting this error when I use it in a fields_for creation.
迁移 -
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
任何帮助将不胜感激,谢谢!
Any help would be massively appreciated, thanks!
推荐答案
多态关联不会生成 build_xxx 方法.只有当您知道要创建的产品类型时,您才能创建新产品:
Polymorphic associations don't generate the build_xxx methods. You can create a new product only if you know what kind of product you want to create :
#Creating a new OrthosisSpecification product associated with @order :
@order.product = OrthosisSpecification.new
文档:http://api.rubyonrails.org/classes/ActiveRecord/关联/ClassMethods.html
这篇关于多态关联未定义方法`build_product'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!