0

导轨 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)

将返回每个父母及其孩子。

每个孩子如何还包括对其父母的引用,以便在序列化期间使用?

例如,采用 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"
                    }
                }
            ]
        }
    }
]
4

2 回答 2

1

您应该覆盖模型to_json上的方法Child

class Child
  belongs_to :parent

  def to_json
    attributes.merge(parent: parent.attributes).to_json
  end
end
于 2012-05-15T19:48:03.227 回答
1
@parents = Parent.find(:all, :include => {:children => :parent})
于 2012-05-15T19:56:08.050 回答