2017-11-28 4 views
0

APIを使用していて、Has_manyアソシエーションを使用しています。父を作成するときにモデルを作成したいので、accepts_nested_attributesを使用することにしました。 そして私ドンは「_attributes」接尾辞を使用している場合、それは私にエラーを発生させ、私の知識に基づいて:APIで'_attributes'のネストされたアトリビュートを受け入れるサフィックス

ActiveRecord::AssociationTypeMismatch

私はポスト依頼のためにこれを行う:

{ 
    "content": { 
     "name": "Teste", 
     "schedulings_attributes":[ 
      { 
       "days_attributes": [ 
         { 
          "start": "2011-10-28", 
          "end": "2010-09-07" 
         }, 
         { 
          "start": "2012-08-30", 
          "end": "2017-06-31" 
         } 
        ], 
        "hours_attributes": [ 
         { 
          "start": "2000-01-01T01:51:30.000Z", 
          "end": "2000-01-01T15:03:11.000Z" 
         }, 
         { 
          "start": "2000-01-01T02:23:39.000Z", 
          "end": "2000-01-01T00:37:51.000Z" 
         } 
        ], 
        "week_attributes": { 
         "monday": true, 
         "thursday": true, 
         "wednesday": true, 
         "tuesday": true, 
         "friday": true, 
         "saturday": true, 
         "sunday": true 
       } 
      } 
     ] 
    } 
} 

事があります、私は '_attributes'接尾辞を望んでいません。 アクティブなレコードにエラーを発生させることなくそれを取る方法はありますか?コントローラーで何らかの治療をしていますか?

答えて

0

私は治療でこれを行う方法を発見しました。上記の方法では

def scheduling_treatment(treated_params) 
    treated_params[:schedulings].map do |attributes| 
     attributes[:days_attributes] = attributes.delete(:days) 
     attributes[:hours_attributes] = attributes.delete(:hours) 
     attributes[:week_attributes] = attributes.delete(:week) 
    end 
    treated_params 
end 

、私はキーのスケジューリングを受信し、私は、キーを取得し、古いキーを削除し、接尾辞を持つ新しい「_attributes」のためにそれを交換し、それをマッピングします。 コントローラの内部:

def content_params 
    new_params = params.require(:content).permit(:id, :name, schedulings: [ 
     days: [:start, :end], 
     hours: [:start, :end], 
     week: [:monday, :thursday, :wednesday, :tuesday, :friday, :saturday, :sunday]]) 
     new_params = scheduling_treatment(new_params) 
     new_params[:schedulings_attributes] = new_params.delete(:schedulings) 
     new_params.permit! 
end 
関連する問題