在模型横幅
中belongs_to :segment
belongs_to :basic_component
has_many :state_banners, dependent: :destroy
has_many :states, through: :state_banners
scope :banner_have_zero_cities, lambda { includes(state_banners: :state_banner_cities).where(state_banner_cities: {state_banner_id: nil}) }
scope :banner_by_state, lambda { |state_id| where("state_banners.state_id = ?", state_id) }
scope :banner_by_city, lambda { |city_id| joins(state_banners: :state_banner_cities).where("state_banner_cities.city_id = ?", city_id) }
在控制器中
def scoped_collection
@banners_cities = Banner.banner_by_city(city_id)
@banners_states =Banner.banner_by_state(city.state_id).banner_have_zero_cities
@banners = @banners_cities.concat(@banners_states)
return @banners.joins(:basic_component)
end
@ banners_states.size => 1
@ banners_cities.size => 2
@ banners_states.merge(@banners_cities)
SQL(0.2ms)SELECT DISTINCT banners
。id
FROM banners
INNER JOIN state_banners
ON state_banners
。banner_id
= banners
。 id
内部加入state_banner_cities
state_banner_cities
。state_banner_id
= state_banners
。id
WHERE(state_banners.state_id = 3)和state_banner_cities
。state_banner_id
IS NULL和(state_banner_cities.city_id =' 260')LIMIT 25 OFFSET 0
=> []
我需要3
我尝试concat
@banners = @ banners_cities.concat(@banners_states) @ banners.size => 3
但
@ banners.joins(:basic_component).order(" basic_component.order asc")。size => 2
CACHE(0.0ms)SELECT COUNT(count_column)FROM(SELECT 1 AS count_column FROM banners
INNER JOIN state_banners
ON state_banners
。banner_id
= banners
。id
内部加入state_banner_cities
state_banner_cities
。state_banner_id
= state_banners
。id
内部加入basic_components
basic_components
。id
= banners
。basic_component_id
WHERE(state_banner_cities.city_id =' 260')LIMIT 25 OFFSET 0)subquery_for_count
:(,帮助
答案 0 :(得分:0)
您的帖子有点难以理解,但在查询结束时尝试.limit(3)
?