在rails 4中生成嵌套对象json响应

时间:2013-10-31 09:20:03

标签: ruby-on-rails json

我是rails的新人。我有两个故事和场景。故事has_may场景和场景属于故事。当我打电话给'/stories/1/scenes.json'然后我想要这个输出

“故事”:[         {

        "name": "akbar and bilber",
        "description": "some description", 
        "story_type": "simple",
        "state": "active",
        "scenes":{
                    "id":"1" 
                    "name": "Akber's introduction",
                    "description":"Akber is king"
                 },
                 {
                    "id":"2" 
                    "name": "bilber's introduction",
                    "description":"bilber's is consultant of akber"
                 },
       "created_at": "2013-09-22T16:32:41.050Z", 
       "updated_at": "2013-09-22T16:32:41.050Z", 
     }]

以下是型号:

       class Story < ActiveRecord::Base
            has_many :scene
       end
       class Scene < ActiveRecord::Base
         belongs_to :story
      end

我需要在这些控制器和show.json.jbulder文件中编写。

1 个答案:

答案 0 :(得分:0)

你必须在场景动作中编写这个部分,你还需要使用json库。

@story = Story.find(params[:id])
render :json => @story.scenes.to_json

你必须在故事模型中纠正你的错误has_many应该是复数而不是单数

class Story < ActiveRecord::Base
   has_many :scenes
end