Dougui
Dougui

Reputation: 7230

Skip extra request made by ActiveRecord

In a rails application, I do some requests on an external database. In newrelic, when I look at the SQL requests I have this :

2.997   718 ms      SHOW FULL FIELDS FROM `whale`
3.717   721 ms      SHOW VARIABLES WHERE Variable_name = 'character_set_client'
4.440   728 ms      SHOW TABLES LIKE 'whale'
5.169   668 ms      SHOW CREATE TABLE `whale`
5.839   731 ms      SELECT id, `whale`.`name` FROM `whale` 

As you can see, all requests take a long time so I want to minimize them. I only need the last result.

This is my simple controller :

class AnimalsController < ApplicationController
  def index
    MicsPix.pluck(:id, :name)
    render text: 'ok'
  end
end

And my model :

class MicsPix < ActiveRecord::Base
  establish_connection(:otherdb)
  def self.table_name
    "whale"
  end
end

Is there a solution to skip queries than I don't use? I don't necessarily want to use ActiveRecord.

Upvotes: 1

Views: 91

Answers (1)

Albin
Albin

Reputation: 3012

I'm not certain where the extra queries arise but i have a suggestion on how to remove them

c = ActiveRecord::Base.establish_connection(
  :adapter  => "mysql2",
  :host     => "localhost",
  :username => "root",
  :password => "",
  :database => "mydatabase"
)

sql = "SELECT id, `whale`.`name` FROM `whale`"
res = c.connection.execute(sql)

then reset db connection to default.

this code works for me, and I can get results from an external db with only query being executed. I did this in a controller method when I tried it out but I think it would be more neat in the model. As far as I understand the establish_connection(:otherdb) does the same as I do when I produce my c. So I think you could write something like this in your MicsPix

def get_list
  sql = "SELECT id, `whale`.`name` FROM `whale`"
  connection.execute(sql)
end

this returns and mysql res object which is quite similar to arrays but not quite.

regards /Albin

Upvotes: 1

Related Questions