2013-04-28 56 views
1

我有一個叫做App.Routine的has_many活動的嵌套資源。當我發的帖子這裏是我的有效載荷:發佈從Ember.js到Rails API的嵌套資源失敗。

{程序:{名稱:測試名,活動內容:[{名稱:測試名},{名稱:測試名}]}}

這將返回500錯誤:

的ActiveRecord :: AssociationTypeMismatch在RoutinesController#創建

活動(#32627220)預計,得到的ActiveSupport :: HashWithIndifferentAccess(#33577656)

我的Rails API是使用ActiveModelSerializers:

class RoutineSerializer < ActiveModel::Serializer 
    attributes :id, :name 

    has_many :activities, embed: :ids 
end 

class RoutinesController < ApplicationController 
    respond_to :json 
    def create 
    routine = Routine.create(params[:routine]) 
    end 

我相信我的問題在於我如何處理我的routines_controller.rb中的創建操作。 Rails不喜歡我如何返回例程JSON內的活動的散列,但我無法弄清楚處理這個問題的正確方法。

+0

你有沒有解決這個問題。有類似的問題? – Undistraction 2013-05-12 17:40:49

+0

@Pedr - 可惜沒有。它似乎是Rails不接受我發送的JSON的問題。如果我從App.store中刪除了{embedded:'always'},則會爲具有「parent_id」的子級的父級和子級發送2個單獨的JSON帖子。以這種方式提交我的POST是成功的,但是我只想發送帶有嵌入式父/子對象的1帖子。遵循這個例子[https://github.com/dgeb/ember_data_example](https://github.com/dgeb/ember_data_example),我不知道我在做什麼不同,會導致錯誤。 – kevinml 2013-05-19 18:50:49

+0

恥辱。感謝更新。 – Undistraction 2013-05-19 19:12:28

回答

0

我的原始問題確實是與我的Rails API。我再次追蹤@ dgeb的例子,並意識到我對強參數知之甚少。謝天謝地,這裏有一個Railscast!一旦我正確實施,我很好去!

在我的Gemfile中添加了「gem strong_parameters」。然後,我父控制器上的#create函數調用update_parameters函數,我首先創建並保存父項,然後遍歷子項並保存它。

從丹·格布哈特的燼數據例如:

def permitted_params 
    params.require(:contact).permit(:first_name, 
           :last_name, 
           :email, 
           :notes, 
           phone_numbers: [:id, :number]) 
end 

def update_contact(contact) 
    contact_params = permitted_params 
    phone_numbers_param = contact_params.extract!(:phone_numbers) 
    phone_numbers_param = phone_numbers_param[:phone_numbers] 
    phone_numbers_param ||= [] 

    # Because updates to the contact and its associations should be atomic, 
    # wrap them in a transaction. 
    Contact.transaction do 
    # Update the contact's own attributes first. 
    contact.attributes = contact_params 
    contact.save! 

    # Update the contact's phone numbers, creating/destroying as appropriate. 
    specified_phone_numbers = [] 
    phone_numbers_param.each do |phone_number_params| 
     if phone_number_params[:id] 
     pn = contact.phone_numbers.find(phone_number_params[:id]) 
     pn.update_attributes(phone_number_params) 
     else 
     pn = contact.phone_numbers.create(phone_number_params) 
     end 
     specified_phone_numbers << pn 
    end 
    contact.phone_numbers.each do |pn| 
    pn.destroy unless specified_phone_numbers.include?(pn) 
    end 
    end 

    # Important! Reload the contact to ensure that changes to its associations 
    # (i.e. phone numbers) will be serialized correctly. 
    contact.reload 

    return true 
    rescue 
    return false 
    end