0

我想为我的项目主页制作一个翻转菜单。这将显示在网站的所有页面中。主菜单项是SHOWSPROGRAMS。当有人滚动这些按钮时,所有程序都会在弹出的 div 中列出。(程序是我的模型的名称,它是我用于节目、电影、电视节目等的通用名称。)

现在...

以下是我的联想:

程序.rb

class Program 
  include Mongoid::Document
  include Mongoid::Timestamps

  field :title
  field :content

  belongs_to :program_category

end

程序类别.rb

  class ProgramCategory 
    include Mongoid::Document
    include Mongoid::Timestamps

    field :title
    field :content

    has_many :programs

  end

我需要让program.titles 显示在我的菜单中。像这样:

SHOWS         PROGRAMS
  \- Lost        \- Ellen
  \- Dexter      \- Marta Stuart
  \- Alf         \- Jey Leno Show

嗯......我现在这样做:

home_controller.rb

类 HomeController < ApplicationController

 def index
     @menu_programs = Program.all.where(program_category_id: "50a7c373ce3a6bcc0a000006").limit(10)    #Yes, i think it's lame too...
     @menu_shows = Program.all.where(program_category_id: "50a67f36ce3a6b840d000007").limit(10) # And yes I'm using MonoDB and Mongoid
  end

是的...它们是program_category_id非常硬编码的!

我觉得像...

这不是最佳做法!

问题是:

显示关联模型中的菜单项的最佳做法是什么?我听说过一些叫做“急切加载”的东西,有人可以解释一下吗?由于 n + 1 个问题,我有 36 个查询...

欢迎任何建议。

谢谢你。

4

2 回答 2

0

它非常简单,只需使用

 @menu_programs = Program.where(program_category_id: "50a7c373ce3a6bcc0a000006").include(:program_cateory).limit(10)
 @menu_shows = Program.where(program_category_id: "50a67f36ce3a6b840d000007").include(:program_cateory).limit(10) 

请注意,我已从您的查询中删除 .all 。

于 2012-11-21T09:52:41.063 回答
0

问题的答案What is best practice to show menu items from associated models?是:

我认为使用片段缓存。它比急于加载恕我直言更重要。

于 2012-12-05T17:11:13.697 回答