在Topic
模型中:
class Topic < ActiveRecord::Base
has_many :choices, :dependent => :destroy
accepts_nested_attributes_for :choices
attr_accessible :title, :choices
end
在 POST 创建期间,params
提交的是:choices
,而不是:choices_attributes
Rails 预期的,并给出错误:
ActiveRecord::AssociationTypeMismatch (Choice(#70365943501680) expected,
got ActiveSupport::HashWithIndifferentAccess(#70365951899600)):
有没有办法配置accepts_nested_attributes_for
接受参数传递choices
而不是choices_attributes
JSON 调用?
目前,我在控制器中创建了属性(这似乎不是一个优雅的解决方案):
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