单个表上的多个字符串查询

时间:2012-09-17 01:31:58

标签: sql ruby-on-rails ruby-on-rails-3

为游戏预告片创建一个网站,在头版我根据他们的类别组织游戏,所以我最终这样做(rails):

  def index
    @newGames = Game.order("created_at DESC").limit(3)
    @casualGames = Game.where("category = 'casual'").limit(9)
    @actionGames = Game.where("category = 'action'").limit(8)
    @strategyGames = Game.where("category = 'strategy'").limit(9)
    @adventureGames = Game.where("category = 'adventure'").limit(8)
    @puzzleGames = Game.where("category = 'puzzle'").limit(9)
  end

有没有办法完成同样的事情,但没有在黑貂桌上进行6次单独的查询?

由于

1 个答案:

答案 0 :(得分:0)

由于您的搜索参数不同,多次查询DB是不可避免的。但是你可以让你的控制器变瘦。在Game类中创建一个类方法,并在哈希中收集并返回所需的所有内容。

<强> Game.rb

def self.for_index_page
    games = {}
    games.merge!(new: order("created_at DESC").limit(3))
    games.merge!(casual: category_with_limit('casual', 9)
    games.merge!(action: category_with_limit('action', 8)
    ...
end

def self.category_with_limit(category, limit)
    where(category: category).limit(limit)
end

<强> GamesController.rb

def index
    @games = Game.for_index_page
end

<强> index.erb

<%=@games[:new] %>
<%=@games[:casual] %>

...
相关问题