Question

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.

Était-ce utile?

La solution

This is the simplest way:

array = res.collect{|row| row['url_list']}

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top