简体   繁体   中英

How to return the parent on a one-to-many association?

Rails 3.0.4

Given the following relationship

class Child < ActiveRecord::Base
  belongs_to   :parent
end

class Parent < ActiveRecord::Base
   has_many  :children
end

Using

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

Will return every parent with its children.

How can each child also include a reference to its parent so that can be used during serialisation?

Eg in a JSON format that would look like:

[
    {
        "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"
                    }
                }
            ]
        }
    }
]

You should override to_json method on Child model:

class Child
  belongs_to :parent

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM