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

时间:2016-07-21 19:36:27

标签: ruby-on-rails mongoid nested-attributes

我试图让iphone用户能够同时创建一个学校和多个管理员。但是,当我尝试使用嵌套属性保存学校时,它返回错误管理员无效

学校模式

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"}

1 个答案:

答案 0 :(得分:0)

试试这个:

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,因此在将Admin分配给school_params时,系统会自动将其分配给新的School.new对象。您无需在那里明确构建管理员。

您获得的错误是因为您正在构建管理员admin = school.admins.build但未向其分配任何属性,因此验证在此Admin对象上失败。所以,你可以完全跳过这一行并尝试我的解决方案。