I have a bit of a complex situation. I am building an iPhone app with a rails backend. There are two model objects, a chat session and a person. They are defined as follows:
class Person < ActiveRecord::Base
belongs_to :chatsession
end
class Chatsession < ActiveRecord::Base
has_many :people
belongs_to :leader, :class_name => "Person"
end
The leader is essentially the main person for that specific chat session. Now from my iPhone app I want to be able to create a Chatsession with the leader in one call (generally network calls are expensive on the iPhone and so I want to avoid creating a Person object and then a session object).
A possible JSON request might look like :
{"chatsession": {"leader": {"name":"mary","device_id":"1111"}}}
On my chatsession controller in the create method I want to be able to suck in this JSON and have it create both a new chat session object and the associated person object.
The relevant code to do this would be:
class ChatsessionController < ApplicationController
def create
@chatsession = Chatsession.new(params[:chatsession])
end
In my functional test it works with the following code:
test "should create session" do
# people(:one) is retrieving from a fixture
post :create, :chatsession => { :leader => people(:one) }
assert_response :success
end
This works great. But to create the equivalent json doesn't seem to work. It is expecting some kind of Person object and I don't know how to represent that. I have looked at the following way of solving the issue.
http://www.rogue-development.com/blog2/2009/05/creating-nested-objects-with-json-in-rails/
Is this the best solution or am I missing something?