は私が持っている問い合わせるこのは、アレイに保存、ただ1件のクエリ検索を行うと、複数の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
何Iすべての "textos"モデルに対して1つのクエリを実行し、次に配列などの内部を検索して特定の変数を取得することが必要です。あなたはすべてのActiveRecordオブジェクトの配列を取得し、必要なデータを格納するハッシュに変換する必要があります
@texto_historia = @texto.find { |a| a.title = "História"}
多くのおかげです。この回答は私に本当にクールな方法を教え、自分のコードのelegancyを改善しました。 :) – pedrozath