只进行一次查询搜索,将其保存到数组,然后只搜索数组而不是执行多个SQL查询

时间:2012-03-18 14:46:38

标签: sql ruby-on-rails

我有这个

class PagesController < ApplicationController
def index
    @textos = Texto.all
    @texto_historia         = Texto.where(:title => "História").first.contents
    @texto_capas_para_sofa  = Texto.where(:title => "Capas para Sofá").first.contents
    @texto_cortinas         = Texto.where(:title => "Cortinas").first.contents
    @texto_almofadas        = Texto.where(:title => "Almofadas").first.contents
end

SQL输出是:

  ←[1m←[36mTexto Load (2.0ms)←[0m  ←[1mSELECT "textos".* FROM "textos"←[0m
  ←[1m←[35mTexto Load (1.0ms)←[0m  SELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Hist├│ria') LIMIT 1
  ←[1m←[36mTexto Load (0.0ms)←[0m  ←[1mSELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Capas para Sof├í') LIMIT 1←[0m
  ←[1m←[35mTexto Load (1.0ms)←[0m  SELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Cortinas') LIMIT 1
  ←[1m←[36mTexto Load (1.0ms)←[0m  ←[1mSELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Almofadas') LIMIT 1←[0m
  ←[1m←[35mTexto Load (0.0ms)←[0m  SELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Informa├º├╡es de Contato') LIMIT 1

我想要的只是对所有“textos”模型进行一次查询,然后在数组或类似内容中搜索以获取特定变量。

2 个答案:

答案 0 :(得分:3)

您需要获取所有ActiveRecord对象的数组,并将其转换为存储所需数据的哈希值。

@textos = Texto.all.inject({}) {|h, obj| h[obj.title] = obj.contents; h }

然后,您就可以使用@textos["title"]访问您的内容。

答案 1 :(得分:1)

我想你想要find or find_all选项:

@texto_historia = @texto.find { |a| a.title = "História"}