Skip to content

Instantly share code, notes, and snippets.

@ysinc88
Last active August 29, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysinc88/6086d46ec9e28c692c87 to your computer and use it in GitHub Desktop.
Save ysinc88/6086d46ec9e28c692c87 to your computer and use it in GitHub Desktop.
Create json nested attributes
class UsersController < ApplicationController
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
private
def user_params
params.require(:user).permit(
:first_name,
:last_name,
phones_attributes: [:user_id,:tel]
end
end
class Phone < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :phones
accepts_nested_attributes_for :phones
end
//I am not passing anything to phones[]
{
"id": 42,
"first_name": null,
"last_name": null,
"phone": "97226491304",
"balance": null,
"password_digest": "1234",
"created_at": "2015-08-19 19:54:20 UTC",
"phones": [],
"courses": [],
"course_count": 0
}
curl -H "Content-Type: application/json" -X POST -d '{"first_name":"yoyo","last_name":"popo","phones_attributes":[{"tel":"12127773456"}]}' http://localhost/users.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment