我正在尝试使用嵌套资源的集合创建新对象。当我发布我的json时,我得到:
ActiveRecord::AssociationTypeMismatch: FormLabel(#70306552439440) expected, got Hash(#70306480154920)
这是我的代码:
# form.rb
class Form < ActiveRecord::Base
has_many :form_labels
validates_presence_of :name
end
# form_label.rb
class FormLabel < ActiveRecord::Base
belongs_to :form
validates_presence_of :form
validates_presence_of :text
end
# form_representer.rb
module FormRepresenter
include Roar::JSON
property :id
property :name
collection :form_labels
end
# form_label_representer.rb
module FormLabelRepresenter
include Roar::JSON
property :text
end
# form_controller.rb
class FormsController < ApplicationController
include Roar::Rails::ControllerAdditions
def create
form = Form.new
consume!(form)
respond_with(form)
end
当我调试时,这些是参数:
0> params
=> {"name"=>"Address", "form_labels"=>[{"text"=>"foo"}], "format"=>"json", "controller"=>"forms", "action"=>"create", "form"=>{"name"=>"Address"}}
,错误是:
ActiveRecord::AssociationTypeMismatch: FormLabel(#70237358584300) expected, got Hash(#70237286721880)
答案 0 :(得分:0)
错误在于:
collection :form_labels
需要:
collection :form_labels, decorator: FormLabelRepresenter, class: FormLabel
请参阅https://github.com/apotonick/roar-rails/issues/125#issuecomment-172175231