JMa*_*Mac 8 ruby-on-rails ruby-on-rails-4
我有这样的事情:
module Api
module V1
class Order < ActiveRecord::Base
has_many :order_lines
accepts_nested_attributes_for :order_lines
end
end
module Api
module V1
class OrderLine < ActiveRecord::Base
belongs_to :order
end
end
Run Code Online (Sandbox Code Playgroud)
在我的订单控制器中,我允许order_lines_attributes
参数:
params.permit(:name, :order_lines_attributes => [
:quantity, :price, :notes, :priority, :product_id, :option_id
])
Run Code Online (Sandbox Code Playgroud)
然后,我正在调用相应的路线,这将创建一个订单并且所有嵌套order_lines
.该方法成功创建了一个订单,但是一些rails魔术也试图创建嵌套的order_lines.我收到此错误:
Uninitialized Constant OrderLine
.
我需要我的accepts_nested_attributes_for
电话才能意识到这OrderLine
是命名空间Api::V1::OrderLine
.相反,幕后的rails正在寻找OrderLine
没有名称空间的东西.我该如何解决这个问题?
我很确定这里的解决方案只是让 Rails 知道完整的嵌套/命名空间类名。
来自文档:
:
class_name
指定关联的类名。仅当无法从关联名称推断出该名称时才使用它。因此,belongs_to :author 默认情况下会链接到 Author 类,但如果真正的类名是 Person,则必须使用此选项指定它。
我通常看到,class_name 选项将字符串(类名)作为参数,但我更喜欢使用常量,而不是字符串:
module Api
module V1
class Order < ActiveRecord::Base
has_many :order_lines,
class_name: Api::V1::OrderLine
end
end
end
module Api
module V1
class OrderLine < ActiveRecord::Base
belongs_to :order,
class_name: Api::V1::Order
end
end
end
Run Code Online (Sandbox Code Playgroud)