3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Active Record のプレースホルダー付き条件を知る

Posted at

前提

  • 生の SQL 文に引数として値を複数渡したいなと思った時に知ったメソッドです。

環境

  • Ruby On Rails 5.1.6
  • Ruby 2.4.4p296

TL;DR

以下のように、 ActiveRecord の where メソッドにおいて、SQL 文にシンボルで値を複数渡すことができます。これは、 where だけじゃなく、 find_by_sql メソッドでも使えることは確認できています。他のメソッドはどうなんだろう…。

Users.where("created_at >= :start and created_at <= :end",
  {start: '2018-01-01', end: '2018-03-31'})
# "SELECT `users`.* FROM `users` WHERE `users`.`type` IN ('Users') AND (created_at >= '2018-01-01' and created_at <= '2018-03-31')"

Users.find_by_sql(['select * from users where created_at between :start and :end', { start: '2018-01-01', end: '2018-03-31' }])
# select * from users where created_at between '2018-01-01' and '2018-03-31'

参考文献

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?