如何在一对多关联中返回父级?

时间:2012-05-15 19:30:27

标签: ruby-on-rails activerecord

Rails 3.0.4

鉴于以下关系

class Child < ActiveRecord::Base
  belongs_to   :parent
end

class Parent < ActiveRecord::Base
   has_many  :children
end

使用

@parents = Parent.find(:all, :include => :children)

将每个父母带回子女。

每个孩子如何也可以包含对其父级的引用,以便在序列化期间使用?

E.g。采用JSON格式,如下所示:

[
    {
        "parent": {
            "created_at": "2012-05-05T11:29:19Z",
            "id": 1,
            "updated_at": "2012-05-05T11:29:19Z",
            "children": [
                {
                    "created_at": "2012-05-05T11:35:05Z",
                    "id": 1,
                    "updated_at": "2012-05-05T11:35:05Z",
                    "parent": {
                        "created_at": "2012-05-05T11:29:19Z",
                        "id": 1,
                        "updated_at": "2012-05-05T11:29:19Z"
                    }
                }
            ]
        }
    }
]

2 个答案:

答案 0 :(得分:1)

您应该在to_json型号上覆盖Child方法:

class Child
  belongs_to :parent

  def to_json
    attributes.merge(parent: parent.attributes).to_json
  end
end

答案 1 :(得分:1)

@parents = Parent.find(:all, :include => {:children => :parent})