내 모델에 포함되지 않습니다 포함 : 나는 다음과 같은 쿼리를 실행하면 예상대로레일 :
class Contact < ActiveRecord::Base
has_many :addresses
has_many :emails
has_many :websites
accepts_nested_attributes_for :addresses, :emails, :websites
attr_accessible :prefix, :first_name, :middle_name, :last_name, :suffix,
:nickname, :organization, :job_title, :department, :birthday,
:emails_attributes
end
class Email < ActiveRecord::Base
belongs_to :contact
validates_presence_of :account
validates_format_of :account, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
attr_accessible :contact_id, :account, :label
end
을의 emails
가 반환됩니다 :
c = Contact.find(3)
Contact Load (3.2ms) SELECT `contacts`.* FROM `contacts` LIMIT 1
=> #<Contact id: 3, prefix: nil, first_name: "Micah", middle_name: nil, last_name: "Alcorn", suffix: nil, nickname: nil, organization: nil, job_title: nil, department: nil, birthday: nil, created_at: "2011-07-04 23:50:04", updated_at: "2011-07-04 23:50:04">
c.emails
Email Load (4.4ms) SELECT `emails`.* FROM `emails` WHERE `emails`.`contact_id` = 3
=> [#<Email id: 3, contact_id: 3, account: "[email protected]", label: "work", created_at: "2011-07-04 23:50:04", updated_at: "2011-07-04 23:50:04">]
을하지만, :include
를 시도 관계하지 않는 :
c = Contact.find(3, :include => :emails)
Contact Load (0.5ms) SELECT `contacts`.* FROM `contacts` WHERE `contacts`.`id` = 3 LIMIT 1
Email Load (0.8ms) SELECT `emails`.* FROM `emails` WHERE `emails`.`contact_id` IN (3)
=> #<Contact id: 3, prefix: nil, first_name: "Micah", middle_name: nil, last_name: "Alcorn", suffix: nil, nickname: nil, organization: nil, job_title: nil, department: nil, birthday: nil, created_at: "2011-07-04 23:50:04", updated_at: "2011-07-04 23:50:04">
위에서 볼 수 있듯이 SQL은 실행 중이지만 전자 메일은 반환되지 않습니다. 나는 각각의 이메일이 포함 된 모든 연락처를 반환하려고하므로 :joins
은 아무런 효과가 없을 것입니다. 내가 뭘 놓치고 있니?
아마 나는 방법의 목적을 오해. 나는 속성과 함께 각 연락처의 '이메일'을 반환 할 것으로 예상했다. 내 목표는 중첩 된 전자 메일 특성을 포함하여 내 인덱스 작업의 모든 연락처에 대한 JSON 표현을 제공하는 것입니다. 어떤 충고? –
"각 연락처의 내부"란 의미에 따라 다릅니다. 나는 당신이 잘못 생각한 것 같아요,하지만 여전히 당신이 원하는대로하고 싶습니다. 가장 좋은 방법으로 모든 이메일을 미리로드합니다. 따라서 'Contact.find (: all, : include => : emails)'를 실행하면 각 연락처에 전자 메일이 첨부됩니다 (연락처의 직접 속성이 아닌 연관성을 통해). 그 후에 왜 그냥''Contact.find (: all, : include => : emails) .to_json (: include => : emails)'하지 말아야한다. 그 트릭을해야합니다. – Casper
여기에 설명 된 추가 'to_json()'트릭 : http://apidock.com/rails/ActiveRecord/Serialization/to_json – Casper