読んでいたコードで面白いテクニックを使っていたのでメモ。 Rails のActiveRecord のfind 系メソッドは優秀だと思うけど、自分でSQL を書きたい時があると思います。そこで、find_by_sql を使うわけですが、その際、大規模なSQL を書く場合のTips です。 環境 ruby 1.8.7 rails 2.2.2 パラメータによってSQL 自体を変えたい場合 例えば、SQL が以下だったとします。 RDBMS はSQLite3 SELECT * from users where name = xxx; これを扱う、find_by_sql が以下のような感じ。 User.find_by_sql(["select * from users where name = :name", {:name => 'bob'}]) #=> [#<User id: 1, name: "
When you're building a new Rails app, ActiveRecord's defaults will take you far. Querying with .where, inserting with .save -- it's all so easy, and it’s fast enough. But after a while -- when a page of mostly simple content takes a second or more to come back from the server, when you start seeing 504 Gateway Timeout errors coming back from nginx because it's taking too long to process the CSV yo
users = User.find_by_sql(['select * from users where id = ?', 1]) puts users.class.name => "Array" puts users.first.class.name => "User" puts users.first.id => 1 # 名前付きプレースホルダバージョン users = User.find_by_sql(['select * from users where id = :id', {id: 1}]) find_by_sql以外の方法 find_by_sql以外の方法もついでに紹介。 ActiveRecord::Base.connection.select_all 返り値はActiveRecord::Result、各要素はHashになっておりドットアクセスができない。プレースホルダーもA
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く