创建使用Rails嵌套的JSON请求 [英] Creating a nested JSON request with Rails

查看:142
本文介绍了创建使用Rails嵌套的JSON请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有点复杂的局面。我建立了轨后端的iPhone应用程序。有两个模型对象,聊天会话和一个人。它们的定义如下:

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

领导者在本质上是主要负责人对特定聊天会话。现在从我的iPhone应用程序,我希望能够在一个调用中创建与领导者一一解释的:)(一般网络电话是在iPhone上的昂贵,所以我想避免创建一个Person对象,然后会话对象)。

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).

一个可能的JSON请求可能是这样的:

A possible JSON request might look like :

{"chatsession": {"leader": {"name":"mary","device_id":"1111"}}}

在在create方法我希望能够在这个JSON吸并使其同时创建一个新的聊天会话对象中,关联人,对象我一一解释的:)控制器。

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.

相关code要做到这一点是:

The relevant code to do this would be:

class ChatsessionController < ApplicationController
     def create
         @chatsession = Chatsession.new(params[:chatsession])   
     end

在我的功能测试,它适用于以下code:

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

这个伟大的工程。而是要创造同等的JSON似乎并没有工作。它期待某种Person对象的,我不知道如何重新present这一点。我已经看过解决问题的方法如下:

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及更高版本自动处理传入的JSON请求。只要确保你的iPhone应用程序被设置MIME类型JSON。请参见帖子其中还讨论了测试传入的​​JSON的帖子。

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.

这篇关于创建使用Rails嵌套的JSON请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆