Deleted articles cannot be recovered. Draft of this article would be also deleted. Are you sure you want to delete this article?

RailsのActive Recordのwhere条件で、「複数カラムのどれかに一致していればOK」という条件を作る方法です。たとえば、性カラムと名カラムが別れたUserに対して、どちらでもいいので検索文字がヒットしてほしいというパターンのwhere条件です。 🎂 検索対象のカラムが固定されている場合(静的)Userテーブルが、次のような定義だったとします。 User id: integer family_name: string first_name: string created_at: datetime updated_at: datetime すでにOR条件の対象となるカラムが固定されている場合は、次のようなコードになります。 class User < Active Record::Base attr_protected :id scope :search_names_or, l
# Rails 4.1.10 scope1 = User.where(sex: 'male', age: 18) scope2 = User.where(sex: 'female', age: 16) # 条件ごとに括弧をつけるために Arel::FactoryMethods#grouping を使う。 condition1 = User.arel_table.grouping(scope1.where_values.reduce(:and)) condition2 = User.arel_table.grouping(scope2.where_values.reduce(:and)) User.where(condition1.or(condition2)).to_sql #=> "SELECT `users`.* FROM `users` WHERE ((`users`.`sex` =
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く