LoginSignup
9
4

More than 5 years have passed since last update.

Ransackで A and (B or C)

Posted at

自分用メモ

条件A = users.name like %山田%
条件B = users.email like %gmail.com%
条件C = users.address like %東京都%

app/controllers/users_controller.rb
def index
  @q = User.search(params[:q]))
  @q.build_grouping unless @q.groupings.any?
  @users = @q.result
end
app/views/users/index.html.haml
= search_form_for @q do |f|
  = f.search_field :name_cont
  = f.grouping_fields do |g|
    = g.hidden_field :m, value: 'or'
    = g.search_field :email_cont
    = g.search_field :address_cont

こんな感じのSQLが作成される

SELECT  "users".* FROM "users"
WHERE ("users"."name" ILIKE '%山田%'
       AND ("users"."email" ILIKE '%gmail.com%'
            OR "users"."address" ILIKE '%東京都%'))

参考

9
4
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
9
4