2012-06-04 4 views
8

残りのAPIでモデルを保存する際に問題が発生しました。モデルの保存時にActiveRecord :: AssociationTypeMismatchが発生しました

{ 
    "card" = > { 
     "miscellaneous" = > "Obervations diverses", 
     "heater" = > "0", 
     "water_quality" = > "", 
     "customer" = > { 
      "id" = > "2", "house_name" = > "house_name2", "city" = > "city_2", "lastname" = > "lastname2", "sci" = > "sci2", "postal_code" = > "potal_code_2", "address_line_1" = > "address_line_2", "updated_at" = > "2012-03-05 18:20:57 +0000", "created_at" = > "2012-03-05 18:20:54 +0000", "firstname" = > "firstname2", "address_line_2" = > "address_line_3", "water_used" = > "0" 
     }, 
     "tasks" = > [ 
      { 
      "title" = > "Nettoyage ligne eau", "id" = > "6", "updated_at" = > "2012-02-17 08:40:47 +0000", "created_at" = > "2012-02-17 08:40:47 +0000" 
      }, 
      { 
      "title" = > "Surveillance", "id" = > "4", "updated_at" = > "2012-02-17 08:40:47 +0000", "created_at" = > "2012-02-17 08:40:47 +0000" 
      } 
     ] 
    } 
} 

アクション作成マイ:私はこのようなJSONを送信すると

class Card < ActiveRecord::Base 
    belongs_to :customer 

    has_many :card_tasks 
    has_many :tasks, :through => :card_tasks 

    accepts_nested_attributes_for :tasks 
    accepts_nested_attributes_for :card_tasks 
    accepts_nested_attributes_for :customer 

end 


class CardTask < ActiveRecord::Base 
    belongs_to :task 
    belongs_to :card 

    accepts_nested_attributes_for :task 
    accepts_nested_attributes_for :card 
end 

class Task < ActiveRecord::Base 
    has_many :cards, :through => :card_tasks 
    has_many :card_tasks 
end 

:これを行う際

def create 
     card = Card.new(params[:card]) 
     if (card.save) 
     respond_with({ :card => card} , :location => nil, status: :created) and return 
     end 
     respond_with({ :errors => card.errors }, :location => nil, status: :unprocessable_entity) and return 
    end 

を、私は多くのタスクと関連した一人の顧客を持つカードのモデルを持っています私は持っている:

ActiveRecord::AssociationTypeMismatch (Task(#70249431354580) expected, got ActiveSupport::HashWithIndifferentAccess(#70249421573300)): 
    app/controllers/cards_controller.rb:14:in `new' 
    app/controllers/cards_controller.rb:14:in `create' 

W帽子は間違っていましたか?

答えて

29

問題はJSON構造にあります。レールはtasks_attributesで、tasksではありません。詳細はthis questionを参照してください。

+0

ありがとうございます。私はActiveRecord :: RecordNotFoundを取得しました。(ID = 6のカードでID = 6のタスクを見つけることができませんでした)model.save() – Sebastien

+2

申し訳ありませんが、 。 accepts_nested_attributes_forが役に立たないという推測では、関連付けを変更することはできません。 nested_attributes.rbにパッチを当てたり、サルパッチを作成したり、カスタムハンドラを作成したりすることができます。ここに実装されていない理由の詳細があります:https://github.com/rails/rails/issues/2925 – dimuch

+0

Card.new(params [:card])をやっているだけで、新しいカードを作成することはできません。私のjsonと? – Sebastien

関連する問題