2015-10-14 6 views
8

私はこのようなものがあります:私の命令制御装置においてRailsの4 API - 名前空間モデルのネストされた属性を受け入れ

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 

を、私はorder_lines_attributesのparamを許可:

params.permit(:name, :order_lines_attributes => [ 
         :quantity, :price, :notes, :priority, :product_id, :option_id 
      ]) 

私は、その後のポストを作っています注文を作成し、すべてのネストされた適切なルートに電話するorder_lines。そのメソッドは正常にオーダーを作成しますが、いくつかのレールの魔法は入れ子になったorder_linesも作成しようとしています。このエラーが表示されます:

Uninitialized Constant OrderLine

OrderLineApi::V1::OrderLineに名前を付けられていることを実現するには、コールが必要です。代わりに、シーンの背後にあるレールは、名前空間なしでOrderLineを探しています。この問題を解決するにはどうすればよいですか?

+0

を'class_name:" Api :: V1 :: OrderLine "を' has_many:order_lines'に追加しますか? – basiam

答えて

1

ここでの解決策は、Railsに完全なネスト/名前空間のクラス名を知らせることです。ドキュメントから

:私は通常見

: class_name

Specify the class name of the association. Use it only if that name can't be inferred from the association name. So belongs_to :author will by default be linked to the Author class, but if the real class name is Person, you'll have to specify it with this option.

は、その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 
関連する問題