我试图在我的控制器中为根对象(项目)添加对象数组(在这种情况下为任务)作为返回类型。一个项目有很多任务,我想一次全部保存,但是我不断收到以下错误,表明返回类型不正确。
ActiveRecord::AssociationTypeMismatch (Task(#47457277775360) expected, got {"name"=>"Some task", "start"=>"2019-12-05T03:38:48.555Z", "end"=>"2019-12-14T03:38:48.555Z"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#47457266882220))
我列入白名单的参数就是这样
# whitelist params
params.permit(:name, :description, tasks: [:name, :start, :end])
以上示例返回的数据:
{"name"=>"asdf", "description"=>"zxvccxvzzxcvxcvcxvzxcvz", "tasks"=>[{"start"=>"2019-12-05T03:38:48.555Z", "end"=>"2019-12-14T03:38:48.555Z", "name"=>"Some task"}]}
[编辑]-这是我们正在使用的模型
# app/models/task.rb
class Task < ApplicationRecord
# model association
belongs_to :project
# validation
validates_presence_of :name
end
# app/models/project.rb
class Project < ApplicationRecord
# model association
has_many :tasks, dependent: :destroy
accepts_nested_attributes_for :tasks
# validations
validates_presence_of :name
end
答案 0 :(得分:1)
根据rails文档Nested attributes allow you to save attributes on associated records through the parent
。因此,在强大的参数中,您需要传递这样的属性。
params.permit(:name, :description, task_attributes: [:name, :start, :end])
我建议您将所有参数绑定在一个这样的属性下
params.require(:project).permit(:name, :description, task_attributes: [:name, :start, :end])
所以您必须像
这样从前端发送参数{"project": {"name"=>"asdf", "description"=>"zxvccxvzzxcvxcvcxvzxcvz", "task_attributes"=>[{"start"=>"2019-12-05T03:38:48.555Z", "end"=>"2019-12-14T03:38:48.555Z", "name"=>"Some task"}]}}
您可以阅读https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
中的文档