在 rails api 的 mongoid 文档中保存嵌套属性

Saving nested attributes in mongoid document in rails api

我正在尝试让 iphone 用户能够同时创建学校和多个管理员。但是,当我尝试使用嵌套属性保存学校时 returns 错误 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"}

试试这个:

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 = school.admins.build 但没有为其分配任何属性,因此此 Admin 对象的验证失败。所以,你完全可以跳过这一行,试试我上面的解决方案。