Last active
August 29, 2015 14:27
-
-
Save ysinc88/6086d46ec9e28c692c87 to your computer and use it in GitHub Desktop.
Create json nested attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Phone < ActiveRecord::Base | |
belongs_to :user | |
end | |
class User < ActiveRecord::Base | |
has_many :phones | |
accepts_nested_attributes_for :phones | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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