katahik
katahik

Reputation: 477

OR search with ActiveRecord

Overview

I want to do an OR search with one that is AND search in ActiveRecord

Detail

I want to change the table to be searched by conditional branching depending on the data stored in the record (whether the status value of the item model is accepted this time).

So, I tried conditional branching as shown below, but it ended up being an AND search. What kind of description should I write if I want to search here by OR?

Code

items_controller.rb

@items.each do |item|
  if item.status != 'accepted'
    # search for Item model
    @items = @items.where(name: search_params[:name])
  else
    # search for Master model
    @items = @items.merge(Master.where(name: search_params[:name]))
  end
end

def search_params
  params.permit(
    :name
    )
end

Generated SQL

AND `items`.`name` = 'test'
AND `masters`.`name` = 'test'

I want this SQL

`items`.`name` = 'test'
OR `masters`.`name` = 'test'

Environment

rails 6.0

Upvotes: 0

Views: 42

Answers (1)

melcher
melcher

Reputation: 1601

Support for "or" was added in Rails 5 you can read more about it here. The syntax works like...

@items = Item.joins(:masters) # or some way to join in the other table
@items.where(name: search_params[:name]).or(Master.where(name: search_params[:name]))

Upvotes: 3

Related Questions