VelLes
VelLes

Reputation: 1032

Best way to use MySQL clause "Use index('index_name')" using ActiveRecord

I want to use the SQL clause "Use index('index_name')" to an ActiveRecord query, does anyone knows a good way to do it with Activerecord I wanted to avoid adding string directly to the query.

Upvotes: 5

Views: 1785

Answers (2)

Lloyd Watkin
Lloyd Watkin

Reputation: 505

Just as a follow up, I've just implemented a solution based on James' above but used a scope instead:

  scope :force_index, -> (index) {
    from("#{table_name} FORCE INDEX(#{index})")
  }

Upvotes: 0

James Daniels
James Daniels

Reputation: 6981

I use this in my models:

def self.use_index(index)
  from("#{self.table_name} USE INDEX(#{index})")
end

Upvotes: 3

Related Questions