0

I'm trying to define a method that takes an optional argument representing a table name and passes it to a SQL statement within that method. When I run the code in my program I get an error saying "could not determine data type of parameter $1." What is causing this and how can I solve it?

Here is my code.

def get_all_movies(order='title')
  sql = %{
    SELECT movies.title AS title, movies.year AS year, movies.rating AS rating,
    genres.name AS genre, studios.name AS studio
    FROM movies
    JOIN genres ON movies.genre_id = genres.id
    JOIN studios ON movies.studio_id = studios.id
    ORDER BY movies.#{order};
  }

  db_connection do |conn|
    order = conn.quote_ident(order)
    @results = conn.exec_params(sql, [order]).to_a
  end

  @get_all_movies = true
end

Thanks in advance!

EDIT: Here is the working code:

def get_all_movies(order='title')
  sql = %{
    SELECT movies.title AS title, movies.year AS year, movies.rating AS rating,
    genres.name AS genre, studios.name AS studio
    FROM movies
    JOIN genres ON movies.genre_id = genres.id
    JOIN studios ON movies.studio_id = studios.id
    ORDER BY movies.#{order};
  }

  db_connection do |conn|
    order = conn.quote_ident(order)
    @results = conn.exec(sql).to_a
  end

  @get_all_movies = true
end
Daniel Bonnell
  • 4,817
  • 9
  • 48
  • 88
  • what sql query it generates – anusha Nov 26 '14 at 04:38
  • 1
    Why are you using `exec_params` when you don't have any params? You're trying to supply the `order` value through standard string interpolation, not through a placeholder. – mu is too short Nov 26 '14 at 04:56
  • I was trying before to do it that way until I read another answer that said I needed to do string interpolation instead. Guess I forgot to switch back to exec. It's working now. Thanks! – Daniel Bonnell Nov 26 '14 at 05:04

0 Answers0