Ruby on rails 如何在一对多关联上返回父级?

Ruby on rails 如何在一对多关联上返回父级?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,Rails 3.0.4 考虑到以下关系 class Child < ActiveRecord::Base belongs_to :parent end class Parent < ActiveRecord::Base has_many :children end 将返回每个父对象及其子对象 每个子级如何还包括对其父级的引用,以便在序列化过程中使用 例如,采用JSON格式,如下所示: [ { "parent": {

Rails 3.0.4

考虑到以下关系

class Child < ActiveRecord::Base
  belongs_to   :parent
end

class Parent < ActiveRecord::Base
   has_many  :children
end
将返回每个父对象及其子对象

每个子级如何还包括对其父级的引用,以便在序列化过程中使用

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

您应该在
模型上覆盖
到\u json
方法:

class Child
  belongs_to :parent

  def to_json
    attributes.merge(parent: parent.attributes).to_json
  end
end
class Child
  belongs_to :parent

  def to_json
    attributes.merge(parent: parent.attributes).to_json
  end
end
@parents = Parent.find(:all, :include => {:children => :parent})