我有這個這樣做只是一個查詢搜索,將其保存到一個數組,然後只搜索陣列,而不是做多的SQL查詢
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」模型執行一個查詢,然後在數組內或類似的東西中搜索以獲取特定變量。
非常感謝。這個答案告訴我一個非常酷的方法,並提高了我的代碼的優雅。 :) – pedrozath 2012-03-18 20:16:29