Bhushan Lodha
Bhushan Lodha

Reputation: 6862

How can I refactor following activerecord query into an SQL query

How can I refactor below ActiveRecord query into an SQL query?

where(home_team: Team.search(params, %i[name])).
  or(where(guest_team: Team.search(params, %i[name])))`

Upvotes: 2

Views: 41

Answers (2)

Hoa.Nguyen
Hoa.Nguyen

Reputation: 117

You might consider using Arel.

where(
  %i[home_team guest_team]
    .map { |field| <YourClassModel>.arel_table[field]].in(Team.search(params, %i[name])) }
    .inject(:or)

<YourClassModel>.arel_table this stuff should be moved to another function if you want to come up with my suggestion.

Another way is using Merge and try to break Team.search to the model scope and merge them with your where query.

Upvotes: 0

ray
ray

Reputation: 5552

You can use following,

value = Team.search(params, %i[name])
Klass.where('home_team = ? OR guest_team = ?', value, value)

Upvotes: 1

Related Questions