在Ruby on Rails中序列化JSON嵌套模型

时间:2016-04-10 19:03:51

标签: ruby-on-rails

我是rails的新手,我有两个型号,一个在另一个型号上有一个外键。

我创建了一个控制器和定义的索引方法,它正常工作:

  def index
    @collections = Collection.all
    render json: @collections 
  end

这是这样的:

  

[{ “ID”:1, “标题”:“集   A”, “book_id”:1, “created_at”: “2016-04-10T18:41:32.709Z”, “的updated_at”: “2016-04-10T18:41:32.709Z”}]

我想将book_id字段转换为书籍对象列表,如下所示:

  

[{“id”:1,“title”:“Collection A”,“books”:[{“book_id”:1,“title:   “BOOK_TITLE”},], “created_at”: “2016-04-10T18:41:32.709Z”, “的updated_at”: “2016-04-10T18:41:32.709Z”}]

然后我尝试了:

  def index
    @collections = Collection.all
    render :json => collections.as_json(
                  :include => { :book_title }
                )
  end

但是在给我语法错误,我无法在此文档http://guides.rubyonrails.org/layouts_and_rendering.html

中看到如何正确执行

我正在使用Rails 4.1.0

1 个答案:

答案 0 :(得分:2)

尝试:

  def index
    @collections = Collection.all
    render :json => @collections.as_json(
                  :include => :book
                )
  end

或者如果您只想要:id和:title:

  def index
    @collections = Collection.all
    render :json => @collections.as_json(
                  :include => {:book => {:only => [:id, :title]}}
                )
  end