2011-09-20 3 views
0

Rails 3에서 스코프를 어떻게 사용해야합니까?

첫 번째 :

class CountryList < ActiveRecord::Base 
    has_one :country, :dependent => :nullify 
end 

두 번째 :

class Country < ActiveRecord::Base 
    belongs_to :country_list 
end 

국가와 연관없이 모든 레코드를 포함하는 CountryList 모델에서 범위를 만들어야합니다.

Smth like :

CountryList.all.each do |country_list| 
    country_list.country.nil? 
end 

답변

1

이 같은 STH을 할 수는 :

class CountryList < ActiveRecord::Base 
    def self.without_countries 
    joins(:country). 
    select("country_lists.*, COUNT(countries.id) AS country_count"). 
    group("country_lists.id"). 
    having("country_count = 0") 
    end 
end 

하지만 PLZ주의이 서쪽에서 가장 빠른 쿼리하지 않을 수 있습니다. 더 나은 접근 방법은 ActiveRecord counter_cache를 사용하는 것이지만, 추가 열이 필요하며 일종의 비정규 화입니다. 자세한 내용은 here을 참조하십시오. counter_cache은 단도가 빠릅니다. ActiveRecord를 벗어나지 않아야합니다. 즉, 원시 SQL을 사용하여 데이터베이스를 조작하지 않아도 ActiveRecord ORM을 우회하면 비정규 화로 인해 해를 끼치 지 않습니다.

btw. 메신저 내가 여기에 터미널이없는 당신이

CountryList.all.select do |country_list| 
    country_list.countries.empty? 
end 
1

을 의미 가정하지만 :

class CountryList < ActiveRecord::Base 
    scope :no_country, joins('LEFT OUTER JOIN countries ON (country_list_id = #{id})').where(:countries => {:country_id => nil}) 
end 

내가 # {ID} 부분은 당신에게 경고를 줄 것이다 확신 해요,하지만 난 할 수 없습니다 R3의 올바른 구문을 기억하십시오.

1
class CountryList < ActiveRecord::Base 
    has_one :country, :dependent => :nullify 
    scope :countryless, where(:country_id => nil) 
end 

CountryList.countryless.all 
관련 문제