I am sending a JSON from app1 to app2 whenever a model is created in app1. I need to create a similar model in app2 along with the nested attributes. I am able to create the model but not able to figure out how to create the nested attributes model for the same in app2. How can I do that in the same controller?
models in app1
class Author
has_many :books, dependent: :destroy
accepts_nested_attributes_for :books
end
class Book
belongs_to :author
end
books_controller.rb in app1
def new
@author = Author.new
@books = @author.books.build
end
def create
@author = Author.new(author_params)
if @author.save
redirect_to author_path(@author), notice: 'Author was successfully created.'
else
render :new
end
end
def author_params
params.require(:author).permit(:name, books_attributes: [:id, :book_name, :publisher]) if params[:author]
end
api in app1
def self.create_or_update_author_in_app2(auth)
app2_author = {}
app2_author[:author_id_in_app1] = auth.id
app2_author[:name] = auth.name
app2_author[:app2_books_attributes] = auth.books.as_json(except: 'app1_author_id')
response = API.post( 'create_or_update_author', body: { request: { author_data: author_data, authenticate: {auth_key: key} } } )
end
models in app2
class App2Author
has_many :app2_books
end
class App2Book
belongs_to :app2_author
end
controller in app2
def create_or_update_author
response = params['request']['app2_author']
app2_author = App2Author.find_or_create_by(author_id_in_app1: response['author_id_in_app1'])
author.update!(name: response['name'])
app2_author.update_attributes(response['app2_books_attributes']) unless app2_author
end
At present, App2Author instances are being created in app2 but how can I create the associated books from the same json?
response received by controller in app2
Parameters: {"request"=>{"app2_author"=>{"author_id_in_app1"=>"16", "name"=>"Author 1", "app2_books_attributes"=>[{"id"=>"43", "book_name"=>"Book 1", "publisher"=>"Publisher 1", "created_at"=>"2019-07-25 15:26:57 +0530", "updated_at"=>"2019-07-25 15:26:57 +0530"},
{"id"=>"43", "book_name"=>"Book 1", "publisher"=>"Publisher 1", "created_at"=>"2019-07-25 15:26:57 +0530", "updated_at"=>"2019-07-25 15:26:57 +0530"},
{"id"=>"43", "book_name"=>"Book 1", "publisher"=>"Publisher 1", "created_at"=>"2019-07-25 15:26:57 +0530", "updated_at"=>"2019-07-25 15:26:57 +0530"},
{"id"=>"43", "book_name"=>"Book 1", "publisher"=>"Publisher 1", "created_at"=>"2019-07-25 15:26:57 +0530", "updated_at"=>"2019-07-25 15:26:57 +0530"}]}, "authenticate"=>{"auth_key"=>"my_key"}}}
one to manyrelationship only.