I have the following method which creates and then executes an SQL query:
def edition_authors(edition, authors)
query_string = "contributor_type = ? AND author = ?"
for i in 1..authors.length - 1
query_string += " OR author = ?"
end
return edition.contributors.where(query_string, 'Author', authors)
end
The last line is the one I’m having trouble with. I want the ‘authors’ array to somehow turn into a set of strings. For instance, if the authors array contained [‘James Joyce’, ‘Cory Doctorow’, ‘Cormac McCarthy’], I’d like that last line to read like:
return edition.contributors.where(query_string, 'Author', 'James Joyce', 'Cory Doctorow', 'Cormac McCarthy')
How could I accomplish this?
Depends which rails and which ruby you are using,
ActiveRecord already has this functionality in Rails 3:
Model.where(:my_field => ['Author', 'James Joyce', 'Cory Doctorow', 'Cormac McCarthy'])arr.map{|v| v.to_s.inspect}will get you a comma separated listarr.join(',')will give you a comma separated list, no quotes.Then you can use this string however you wish.