rails 4在哈希中具有关联(作为嵌套的attrs)的反转模型

时间:2015-02-06 04:32:36

标签: ruby-on-rails-4 activerecord nested

  

model User
  has_many :books
model Book
  belongs_to :user

我想要的是

pseudo User.first.with(:books)


result => Hash {user:  {name: "john_doe", 
                  books: {0: {title: "book"}}}}

我怎样才能实现这个目标?

EDIT

我差不多了:User.preload(:books).first - >使用嵌套的retrives模型 但现在如何如上所述串行化?    编辑 做完了!

user = User.preload(:books).first
hash = user.as_json
books = user.books
x = Hash[(0...books.size).zip books]
hash[:books] = x

1 个答案:

答案 0 :(得分:0)

应用/模型/ user.rb

class User < ActiveRecord::Base
  has_many :books

  def as_json(options = nil)
    super({ only: [:id, :name], include: :books })
  end
end

有了这个,您可以像这样使用as_json

>> User.first.as_json
=> {"id"=>1, "name"=>"john_doe", "books"=>[
   {"user_id"=>1, "id"=>1, "title"=>"book", 
    "created_at"=>Fri, 06 Feb 2015 09:25:12 UTC +00:00, 
    "updated_at"=>Fri, 06 Feb 2015 09:25:12 UTC +00:00}]}
>> 

也有一些宝石提供类似的结果。有关详细信息,请查看http://robots.thoughtbot.com/better-serialization-less-as-json