我试图有一个iphone用户能够创建一所学校和多个管理员在同一时间。但是,当我尝试使用嵌套属性保存学校时,它返回错误admins is invalid
学校模式
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
管理模型
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
学校控制器
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: {"school"=>{"school_name"=>"Curry College", "admins_attributes"=>{"0"=>{"email"=>"test@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}, "subdomain"=>"api"}
发布于 2016-07-22 14:44:04
试试这个:
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
由于您已允许在控制器中使用admins_attributes
,因此在将school_params
分配给School.new
时,它们将自动分配给新的Admin
对象。您不需要在那里显式地构建一个管理员。
您得到的错误是因为您正在构建一个admin admin = school.admins.build
,但没有为其分配任何属性,因此在此Admin
对象上的验证失败。所以,你可以完全跳过这一行,试试我上面的解决方案。
https://stackoverflow.com/questions/38512934
复制相似问题