วิธีจัดการกับพี่น้องสองคนที่ซ้อนกันโดยมี to_json ถัดไป

เอกสาร to_json ActiveRecord บอกว่า สิ่งนี้ สำหรับการจัดการกับโมเดลที่ซ้อนกันสองโมเดล โดยที่ความคิดเห็นซ้อนอยู่ในโพสต์ : :

  konata.to_json(:include => { :posts => {
                                 :include => { :comments => {
                                               :only => :body } },
                                 :only => :title } })
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true,
        "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
                   "title": "Welcome to the weblog"},
                  {"comments": [{"body": "Don't think too hard"}],
                   "title": "So I was thinking"}]}

สมมติว่าฉันมีโมเดลสองรุ่นที่ซ้อนกัน แต่ไม่ได้ซ้อนกันลึก สมมติว่ามันเป็นโมเดลผู้ใช้และโมเดลความคิดเห็น โมเดลที่ซ้อนกันจะเป็นสิ่งที่ฉันเรียกว่าพี่น้องที่ซ้อนกัน

ฉันต้องการให้ json ของฉันมีลักษณะเช่นนี้:

x = { 
    "Blog": {
        "Comments": [
         {"id":1,"name":"John Doe"},
         {"id":2,"name":"Don Joeh"}
        ],
        "User": [
         {"id":2,"company":"ACME"},
         {"id":4,"company":"BUD"}]
    }
}

เมื่อฉันใช้วิธีรวมสองครั้ง ผลลัพธ์ที่ได้คือชุดของ json ที่ซ้อนกันแบบลึก โดยที่ผู้ใช้เป็นลูกของความคิดเห็น เกิดอะไรขึ้น?!

data.to_json(
        :include => { :blog => {
          :include => [{ :comments => {
            :except => SKIPPED_COLUMNS,
            :methods => [:_type]
          }},
          { :users => {
              :except => SKIPPED_COLUMNS,
              :methods => [:_type]
          }}],
          :except => SKIPPED_COLUMNS,
          :methods => [:_type]
        }},
        :except => SKIPPED_COLUMNS,
        :methods => [:_type]
      )

person JZ.    schedule 05.06.2013    source แหล่งที่มา


คำตอบ (1)


ทำไมคุณถึงมี blog สองครั้ง?

blog.to_json(
    :include => { :blog => {

ฉันคิดว่า blog ตัวที่สองไม่ควรอยู่ในนั้น ลองสิ่งนี้:

blog.to_json(
  :include => [
    {
      :comments => {
        :except => SKIPPED_COLUMNS,
        :methods => [:_type]
      }
    }, {
      :users => {
        :except => SKIPPED_COLUMNS,
        :methods => [:_type]
      }
    }
  ],
  :except => SKIPPED_COLUMNS,
  :methods => [:_type]
)
person Sergey Bolgov    schedule 06.06.2013
comment
มันเป็นเพียงการพิมพ์ผิด มันเก็บไว้ในข้อมูลจริงๆ - person JZ.; 06.06.2013