在Rails中嵌套强参数-预期为AssociationTypeMismatch MYMODEL,得到了ActionController :: Parameters() [英] Nested strong parameters in rails - AssociationTypeMismatch MYMODEL expected, got ActionController::Parameters()
问题描述
我正在渲染一个模型,它是JSON的子书,如下所示:
I'm rendering a model and it's children Books in JSON like so:
{"id":2,"complete":false,"private":false, "books" [{ "id":2,"name":"Some Book"},.....
然后我通过将相同的JSON传递回我的控制器来更新此模型,并且出现以下错误:
I then come to update this model by passing the same JSON back to my controller and I get the following error:
ActiveRecord :: AssociationTypeMismatch(预期为Book(#2245089560),已获得ActionController :: Parameters(#2153445460))
ActiveRecord::AssociationTypeMismatch (Book (#2245089560) expected, got ActionController::Parameters(#2153445460))
在我的控制器中,我正在使用以下内容进行更新:
In my controller I'm using the following to update:
@project.update_attributes!(project_params)
private
def project_params
params.permit(:id, { books: [:id] } )
end
无论我在permit
中将哪些属性列入白名单,我似乎都无法保存子模型.
No matter which attributes I whitelist in permit
I can't seem to save the child model.
我缺少明显的东西吗?
更新-另一个示例:
控制器:
def create
@model = Model.new(model_params)
end
def model_params
params.fetch(:model, {}).permit(:child_model => [:name, :other])
end
请求:
post 'api.address/model', :model => { :child_model => { :name => "some name" } }
型号:
accepts_nested_attributes_for :child_model
错误:
期望ChildModel,获得了ActionController :: Parameters
expected ChildModel, got ActionController::Parameters
尝试此方法无济于事: http://www .rubyexperiments.com/using-strong-parameters-nested-forms/
Tried this method to no avail: http://www.rubyexperiments.com/using-strong-parameters-with-nested-forms/
推荐答案
我正在使用Angular.js&轨道与Rails序列化程序,这对我有用:
I'm using Angular.js & Rails & Rails serializer, and this worked for me:
模型:
- has_many:功能
- accepts_nested_attributes_for:功能
ModelSerializer :
- has_many:features,根目录::features_attributes
控制器:
- params.permit features_attributes:[:id,:enabled]
AngularJS :
-
model.features_attributes中的
- ng-repeat ="feature按feature.id进行跟踪
- ng-repeat="feature in model.features_attributes track by feature.id
这篇关于在Rails中嵌套强参数-预期为AssociationTypeMismatch MYMODEL,得到了ActionController :: Parameters()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!