Ruby On Rails - 减少数据库查询

时间:2017-01-17 13:40:28

标签: ruby-on-rails database ruby-on-rails-4 model controller

在我的应用程序中,我有WebsiteAd模型& website_ads表格,其中包含我可以从我的管理员控制的所有网站广告。

目前,在一个页面中,我会针对每个广告向数据库进行1次查询,并在我的视图中查看该广告是否为active

在我的控制器中:

# START - Desktop ads
def ads_desktop_tablet
  @header_desktop_tablet = ad_placement('header_desktop-tablet')
  @footer_desktop_tablet = ad_placement('footer_desktop-tablet')
  @footer_desktop_tablet_c = ad_placement('footer_desktop-tablet_C')
  @desktop_tablet_b1 = ad_placement('desktop-tablet_B1')
  @desktop_tablet_b2 = ad_placement('desktop-tablet_B2')
  @desktop_tablet_b3 = ad_placement('desktop-tablet_B3')
  @desktop_tablet_s1 = ad_placement('desktop-tablet_S1')
  @desktop_inline_banner = ad_placement('desktop_inline_banner')
  @desktop_inline_video = ad_placement('desktop_inline_video')
  @desktop_tablet_b2_c = ad_placement('desktop-tablet_B2_C')
  @desktop_tablet_b3_c = ad_placement('desktop-tablet_B3_C')
  @desktop_tablet_s1_c = ad_placement('desktop-tablet_S1_C')
  @desktop_tablet_l1 = ad_placement('desktop-tablet_L1')
end
# END - Desktop ads

# START - Mobile ads
def ads_mobile
  @header_mobile = ad_placement('header_mobile')
  @footer_mobile = ad_placement('footer_mobile')
  @mobile_b1 = ad_placement('mobile_B1')
  @mobile_b2 = ad_placement('mobile_B2')
  @mobile_b3 = ad_placement('mobile_B3')
  @mobile_s1 = ad_placement('mobile_S1')
  @mobile_inline_banner = ad_placement('mobile_inline_banner')
  @mobile_b3_c = ad_placement('mobile_B3_C')
end
# END - Mobile ads

在我的帮手中:

def ad_placement(placement)
  WebsiteAd.where(placement: placement).first
end

# I have a method/`def` for each ad like below
def ad_desk_s1_active?
  if desktop_tablet_s1.status == true
    desktop_tablet_s1.ad_tag.html_safe
  end
end

在我看来:

= ad_desk_s1_active?

我知道这不是一个好的做法和正确的方法。如何使这更高效,更少的代码和数据库查询?

1 个答案:

答案 0 :(得分:3)

您可以使用index_by

@ads = WebsiteAd.all.index_by(&:placement)

或仅获取所需广告

placements = %w(header_mobile footer_mobile)
@ads = WebsiteAd.where(placement: placements).index_by(&:placement)

导致哈希

@header_mobile = @ads['header_mobile']

或直接在视图中使用@ads

<%= @ads['header_mobile'] %>