【问题标题】:multiple string queries on a single table单个表上的多个字符串查询
【发布时间】:2012-09-17 01:31:57
【问题描述】:

为游戏预告片制作一个网站,在首页上我根据游戏的类别组织游戏,所以我最终这样做了(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

有没有一种方法可以完成同样的事情,但无需对 sable 表进行 6 次单独的查询?

谢谢

【问题讨论】:

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


    【解决方案1】:

    由于您的搜索参数不同,因此多次查询数据库是不可避免的。但是,您可以使控制器变瘦。在 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] %>
    
    ...
    

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多