【发布时间】:2012-06-18 07:05:09
【问题描述】:
在Topic 模型中:
class Topic < ActiveRecord::Base
has_many :choices, :dependent => :destroy
accepts_nested_attributes_for :choices
attr_accessible :title, :choices
end
在 POST 创建期间,提交的 params 是 :choices,而不是 Rails 预期的 :choices_attributes,并给出错误:
ActiveRecord::AssociationTypeMismatch (Choice(#70365943501680) expected,
got ActiveSupport::HashWithIndifferentAccess(#70365951899600)):
有没有办法配置 accepts_nested_attributes_for 以接受在 JSON 调用中作为 choices 而不是 choices_attributes 传递的参数?
目前,我在控制器中创建了属性(这似乎不是一个优雅的解决方案):
def create
choices = params[:topic].delete(:choices)
@topic = Topic.new(params[:topic])
if choices
choices.each do |choice|
@topic.choices.build(choice)
end
end
if @topic.save
render json: @topic, status: :created, location: @topic
else
render json: @topic.errors, status: :unprocessable_entity
end
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 json