【发布时间】:2013-06-03 23:25:31
【问题描述】:
我有一个名为 App.Routine 的嵌套资源,其中包含多个活动。当我在这里发送帖子时是我的有效负载:
{例程:{name:testName,activities:[{name:testName},{name:testName}]}}
这会返回 500 错误:
RoutinesController#create 中的 ActiveRecord::AssociationTypeMismatch
Activity(#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 中返回活动的哈希值,但我想不出正确的方法来处理这个问题。
【问题讨论】:
-
你有没有解决过这个问题。有类似的问题吗?
-
@Pedr - 不幸的是没有。 Rails 不接受我发送的 JSON 似乎确实是个问题。如果我从 App.store 中删除 {embedded: 'always'},则会为父母和孩子发送 2 个单独的 JSON 帖子,其中孩子具有“parent_id”。以这种方式提交我的 POST 是成功的,但是我只想发送 1 篇带有嵌入的父/子对象的帖子。按照这个例子https://github.com/dgeb/ember_data_example,我不知道我在做什么不同会导致错误。
-
耻辱。感谢您的更新。
-
终于想通了。我能够通过不将子对象嵌入到父对象中来解决问题,因此为父对象发送单独的 POST 到 API,然后为每个包含 parent_id 的子对象再次发送。这不是一个理想的解决方案,所以我回去处理嵌入式父/子 json 请求。我最初的问题确实出在我的 Rails API 上。我再次遵循@dgeb 的示例,并意识到我对强参数了解不多。值得庆幸的是,有一个Railscast!一旦我正确实施,我就可以开始了!