【问题标题】:Rails Render JSON of a has_many, through AssociationRails 通过 Association 渲染 has_many 的 JSON
【发布时间】:2016-05-08 13:08:14
【问题描述】:

我的应用程序中有 3 个模型 艺术家、专辑和歌曲

class Artist < ActiveRecord::Base
    has_many :albums
    has_many :songs, :through => :albums
end

class Albums < ActiveRecord::Base
    has_many :songs
    belongs_to :artist
end

class Albums < ActiveRecord::Base
    belongs_to :albums
end

如何将它呈现为 JSON,其中它返回一个艺术家数组,每个艺术家都有一个属性“专辑”,其中它是每个艺术家的专辑数组,每个专辑都有一个属性 Songs,它是歌曲数组对于每张专辑。像这样

[ {
    id: 1,
    name: Artist_Name,
    albums: [
        {
            id: 1,
            name: Album_Name,
            songs: [{
                id: 1,
                title: Song_Title,
                lyrics: Song_Lyrics
            }]
        }
    ]
}]

【问题讨论】:

    标签: ruby-on-rails json


    【解决方案1】:

    按照 Rails 约定,型号名称应该是单数,其次你的最后一个型号名称应该是歌曲。

    在 Json 中包含嵌套的关联资源 像这样定义你的模型:

    class Artist < ActiveRecord::Base
      has_many :albums
      has_many :songs, :through => :albums
    
      def as_json(options={})
        super(include: { albums: { include:  :songs } })
      end
     end
    
     class Album < ActiveRecord::Base
       has_many :songs
       belongs_to :artist
     end
    
     class Song < ActiveRecord::Base
       belongs_to :album
     end
    

    现在在您的活动唱片艺术家对象上调用 .to_json 将返回嵌套的专辑和歌曲。

    或者你可以直接打电话给Artist.all.to_json(include: {albums: {include: :songs}})

    【讨论】:

      【解决方案2】:

      我会推荐你​​使用 Jbuilder gem https://github.com/rails/jbuilder

      【讨论】:

      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      相关资源
      最近更新 更多