# Conditionally chaining where blocks

**URL:** <https://discourse.rom-rb.org/t/conditionally-chaining-where-blocks/286>\
**Category:** Issues\
**Created:** [November 1, 2018, 6:31pm UTC](https://discourse.rom-rb.org/t/conditionally-chaining-where-blocks/286 "2018-11-01T18:31:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jacquesporveau](https://avatars.discourse-cdn.com/v4/letter/j/49beb7/32.png) [@jacquesporveau](https://discourse.rom-rb.org/u/jacquesporveau)\
**Post date:** [November 1, 2018, 6:31pm UTC](https://discourse.rom-rb.org/t/conditionally-chaining-where-blocks/286/1 "2018-11-01T18:31:11Z")

</div>

Does anyone have any ideas for solving the following problem?

Looking to write a method that takes in a hash that has optional keys and based on whether there are certain keys present they conditionally chain where clauses.

```auto
{
  name: "John",
  age: 23
}

```

Would trigger something like `persons.where(age: 23).where { name.ilike("%John%") }`

But if I passed something like:

```auto
{ age: 23 }

```

Would trigger something like `persons.where(age: 23)`

Thanks!

---

<div class="post-metadata">

**Author:** ![solnic](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.rom-rb.org/solnic/32/279_2.png) [@solnic](https://discourse.rom-rb.org/u/solnic)\
**Post date:** [November 2, 2018, 4:18pm UTC](https://discourse.rom-rb.org/t/conditionally-chaining-where-blocks/286/2 "2018-11-02T16:18:39Z")

</div>

You could do this:

```ruby
conditions = { age: 21, name: "John" }

matching_users = conditions.reduce(users) do |r, (k, v)|
  case v
  when String
    r.where(r[k].ilike("%#{v}%"))
  else
    r.where(k => v)
  end
end

```

Hope this helps.
