Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to create a parent and child object in one POST?

I have two applications, App1 and App2. App1 posts a JSON payload to App2 that includes data for a parent and child object. If the parent object already exists in App2, then we update the parent record if anything has changed and create the child record in App2. If the parent object does not exist in App2, we need to first create it, then create the child object and associate the two. Right now I'm doing it like this:

class ChildController
  def create
    @child = Child.find_or_initialize_by_some_id(params[:child][:some_id])
    @child.parent = Parent.create_or_update(params[:parent])

    if @child.update_attributes(params[:child])
      do_something
    else
      render :json => @child.errors, :status => 500
    end
  end
end

Something feels dirty about creating/updating the parent like that. Is there a better way to go about this? Thanks!

like image 814
Matt Avatar asked Oct 19 '12 18:10

Matt


1 Answers

As a starting point, you'll want to create the association in your model, then include accepts_nested_attributes_for on your Parent.

With the associations created in your model, you should be able to manipulate the relationship pretty easily, because you automatically get a host of methods intended to manage the relationship. For example, your Parent/Child model might look something like this:

In your Parent model:

class Parent < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children

In your Child model:

class Child < ActiveRecord::Base
  belongs_to :parent

Then, you should be able to build associations in your controller like this:

def new
    @parent = Parent.children.build
end

def create
   @parent = Parent.children.build(params[:parent])
end

The nested_attributes property will then allow you to update attributes of the Child by manipulating the Parent.

Here is the Rails API on the topic: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

like image 112
jflores Avatar answered Sep 23 '22 10:09

jflores