나는 국가 모델과 여행 노트 모델이 있습니다. 한 국가에는 많은 여행 노트가 있고 여행 노트는 한 국가에 속합니다. 응용 프로그램/컨트롤러/countries_controller.rb에서레일 activerecord 관계 조인 테이블
class TravelNote < ActiveRecord::Base
default_scope { order(created_at: :desc) }
belongs_to :country
has_many :chapters
before_destroy { draft? }
validate :validates_uniqueness_of_draft, on: :create
enum status: { draft: 0, published: 1, archived: 2 }
enum advice_against: { no: 0, general: 1, tourists: 2 }
scope :country, ->(country_id) { where(country_id: country_id) }
# further methods omitted...
end
class Country < ActiveRecord::Base
default_scope { order(:iso_code) }
has_many :travel_notes
end
:/index.html.haml 응용 프로그램/뷰/국가에서
class CountriesController < ApplicationController
def index
@countries = Country.includes(:travel_notes)
end
# rest of the class omitted...
end
:
@countries.each do |country|
%tr
%td= link_to country.name_de, country_travel_notes_path(country)
%td= TravelNote.published.country(country.id).first.try :published_at
때문에 성능 이유 내가 원하는 TravelNote.published.country (country.id) .first.try : published_at를 제거하십시오. 그 대신 동등한 SQL 쿼리의 배열 대신 더 이상 수백 개의 데이터베이스 쿼리가 없습니다 :
select * from countries
left join travel_notes
on countries.id=travel_notes.country_id
어떻게하면됩니까?
내가 아니다 하지만,'TravelNote.published.joins (: country) .where (: countries => {: id => country.id}) map (& : published_at)'도움이된다면 시도 할 수 있습니다 – Sontya
Sontya에게 감사드립니다. 실제로 도움이되었습니다. – StandardNerd