[英]Saving nested attributes in mongoid document in rails api
Im trying to have an iphone user be able to create a school and multiple admins at the same time. 我试图让一个iphone用户能够同时创建一所学校和多个管理员。 However when I try to save the school using nested attributes it returns the error admins is invalid
但是,当我尝试使用嵌套属性保存学校时,它返回错误admins无效
School Model 学校模式
class School
include Mongoid::Document
include Mongoid::Timestamps
# Callbacks
after_create :spacial
embeds_many :admins
accepts_nested_attributes_for :admins
validates_associated :admins
# Fields
field :school_name, type: String
end
Admin Model 管理员模型
class Admin
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :school
before_create :generate_authentication_token!
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Schools Controller 学校负责人
class Api::V1::SchoolsController < ApplicationController
def show
respond_with School.find(params[:id])
end
def create
school = School.new(school_params)
admin = school.admins.build
if school.save
render json: school, status: 201, location: [:api, school]
else
render json: { errors: school.errors }, status: 422
end
end
private
def school_params
params.require(:school).permit(:school_name, admins_attributes: [:email, :password, :password_confirmation])
end
end
Parameters 参量
Parameters: {"school"=>{"school_name"=>"Curry College", "admins_attributes"=>{"0"=>{"email"=>"test@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}, "subdomain"=>"api"}
Try this: 尝试这个:
class Api::V1::SchoolsController < ApplicationController
def create
school = School.new(school_params)
if school.save
render json: school, status: 201, location: [:api, school]
else
render json: { errors: school.errors }, status: 422
end
end
private
def school_params
params.require(:school).permit(:school_name, admins_attributes: [:email, :password, :password_confirmation])
end
end
As you have permitted admins_attributes
inside your controller, they will be automatically assigned to the new Admin
object when assigning school_params
to School.new
. 正如你所允许
admins_attributes
控制器内,他们将被自动分配给新的Admin
分配时,对象school_params
到School.new
。 You don't need to explicitly build an admin there. 您无需在那里显式构建管理员。
The error you are getting is because you are building an admin admin = school.admins.build
but not assigning any attributes to it, so the validations fail on this Admin
object. 您收到的错误是因为您正在构建admin
admin = school.admins.build
但未admin = school.admins.build
分配任何属性,因此对该Admin
对象的验证失败。 So, you can completely skip this line and try my solution above. 因此,您可以完全跳过此行并尝试上面的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.