开发者

Creating a nested JSON request with Rails

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 funct开发者_运维技巧ional 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?


The post looks like an excellent solution to me.

Which part are you having trouble with?

Rails 2.1 and later automatically handles incoming JSON requests. Just make sure that your iPhone app is setting the mime type to json. See post which also discusses testing incoming JSON in posts.


Couple of pointers:

  • Make sure you are setting both the "Content-Type" and "Accept" header to "application/json". Test this by looking/logging your params; if they are all set correctly, you're good to go.

  • I think you want to have a accepts_nested_attributes_for :leader on your chat session.

  • You may need to bypass the authenticity token; your iPhone won't be sending it along, and by default rails is looking for it on post/put operations.

But your setup and thinking looks fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜