Andy Harvey
Andy Harvey

Reputation: 12663

How to create an Active Record select query with an OR statement?

This should be quite simple, but I can't work out the syntax.

I have an AR query

ActiveRecord::Base.connection.tables.select { |t| t != 'schema_migrations' }

that I want to add an OR statement to

ActiveRecord::Base.connection.tables.select { |t| t != 'schema_migrations' OR 'pg_search_documents' }

What is the correct syntax? Thanks!

Upvotes: 0

Views: 242

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64373

You can use the reject pattern along with array include?, as it makes it easy to add more tables to the rejection list..

ActiveRecord::Base.connection.tables.reject do |t| 
  %w(schema_migrations pg_search_documents).include?(t)
end

Upvotes: 1

Steve
Steve

Reputation: 15736

The correct syntax is:

ActiveRecord::Base.connection.tables.select { |t| t != 'schema_migrations' && t != 'pg_search_documents' }

The code inside the block is just a Ruby expression that needs to return a boolean result so you can use the logical AND operator && to express the logic "table name is not 'schema_migrations' AND table name is not 'pg_search_documents'"

Perhaps a simpler way to express the same logic is to subtract an array of table names that you want to filter out like this:

ActiveRecord::Base.connection.tables - ['schema_migrations', 'pg_search_documents']

Upvotes: 1

Related Questions