Saving nested attributes in mongoid document in rails api -


im trying have iphone user able create school , multiple admins @ same time. when try save school using nested attributes returns error admins invalid

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 , :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 have permitted admins_attributes inside controller, automatically assigned new admin object when assigning school_params school.new. don't need explicitly build admin there.

the error getting because building admin admin = school.admins.build not assigning attributes it, validations fail on admin object. so, can skip line , try solution above.


Comments