簡體   English   中英

如何使用ActiveRecord在Rails中返回關聯的模型對象

[英]How to return associated model objects in Rails with ActiveRecord

我們假設我有以下三個對象:

class Filing < ActiveRecord::Base
    belongs_to :company
    has_many :people , :dependent => :destroy
end

class Company < ActiveRecord::Base
    has_many :filings
end

class Person < ActiveRecord::Base
    belongs_to :filing
end

我正在嘗試發出一個請求,返回與其關聯公司的歸檔以及包含其關聯人員的數組 這用於GET歸檔/:id的API請求

我看到了使用ActiveRecord連接表的文檔,但是當我運行以下查詢時:

Filing.joins(:people,:company)

它似乎不包括結果集中的關聯人員或公司。 如果不返回相關數據,我有點擔心為什么我會加入。 我在這里錯過了什么? 我應該運行什么查詢?

更新

正如評論中所提到的那樣。 我希望能夠生成以下輸出:

{ "filing" => { "filing_id" => 123, "company" => { ... }, "people" => [{"person_id" => 1}, {"person_id" => 2}] } }

在評論者的幫助下,我最終找到了答案。 所有需要調用的是:

Filing.find( id , :include => [:company,:people] )

我想你想要的是以下內容:

Filing.includes([:company, :people]).where(:filing => [:id => 756])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM