Sql 单个表上的多个字符串查询
制作一个游戏预告片网站,在头版我根据游戏类别组织游戏,因此我最终做了以下工作:Sql 单个表上的多个字符串查询,sql,ruby-on-rails,ruby-on-rails-3,Sql,Ruby On Rails,Ruby On Rails 3,制作一个游戏预告片网站,在头版我根据游戏类别组织游戏,因此我最终做了以下工作: 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
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次单独的查询
谢谢因为您的搜索参数不同,多次查询数据库是不可避免的。但是,您可以使控制器变瘦。在游戏类中创建一个类方法,收集并返回散列中所需的所有内容 Game.rb GamesController.rb 索引.erb
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
def index
@games = Game.for_index_page
end
<%=@games[:new] %>
<%=@games[:casual] %>
...