0

I am trying to retrieve a list of URLs from my Postgres DB, using the following method...

def get_urls(site_id)
  conn = PGconn.open(:dbname => 'my_listings')
  res = conn.exec("SELECT url_list FROM listings WHERE site_id=#{site_id}")
  array = []
  count = 0
  res.each do |row|
    row.each do |column|
      array[count] = column
      count += 1
    end
  end
  array
end

Then, when I run the code...

my_array = get_urls(3)
my_array[0]

I get a return value of

 => ["url_list", "http://www.somesite.com"] 

So it is giving me both the column name and the value of the data, where I am trying to populate the array with just the values.

HMLDude
  • 1,547
  • 7
  • 27
  • 47

2 Answers2

2

This is the simplest way:

array = res.collect{|row| row['url_list']}
mechanicalfish
  • 12,696
  • 3
  • 46
  • 41
1

The docs can be found here: http://deveiate.org/code/pg/PG/Result.html

The correct way is to just call the values method:

def get_urls(site_id)
  conn = PGconn.open(:dbname => 'my_listings')
  res  = conn.exec("SELECT url_list FROM listings WHERE site_id=#{site_id}")
  conn.close # Close the connection again.
  res.values # Return a list of values.
end
hirolau
  • 13,451
  • 8
  • 35
  • 47
  • Just curious what the downside of not closing the connection would be? – HMLDude Nov 11 '13 at 20:05
  • Not that much, but if the servers has a limited number of allows of connections it could be a problem if the function is called many times . Then is recommended to only once in the beginning, perform all queries and then close it when the script is finished. – hirolau Nov 11 '13 at 21:23