views:

34

answers:

2

Hi,

I am sending data via get and I need to put it into a int array to be used in a find. here is my code :

@found = Array.new
  params['candidate'].each do |c|
  @found << c.to_i
  end

My url looks like this

http://localhost:3000/export/candidate?candidate[]=3&amp;candidate[]=4&amp;commit=Export

If it makes any difference I am using it for this find

@candidate = Candidate.find(:all, :conditions => ["candidates.id IN ?", @found]) 

But currently it doesn't put it in a real array because I get this error

Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '4)' at line 1: SELECT * FROM `candidates` WHERE (candidates.id IN 4,2)

The brackets are missing around the array

Thanks and good morning!

Alex

+2  A: 

Just put parentheses around your ?

@candidate = Candidate.find(:all, :conditions => ["candidates.id IN (?)", @found]) 

Also, your first snippet can be collapsed down to:

@found = params['candidate'].map(&:to_i)
Gareth
Alex
It's an easy way of passing a block which just calls the given method on the argument passed into the block. There's a good explanation at http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html
Gareth
Thanks, ruby is such a cool language!
Alex
A: 

The entire conversion you are making is unnecessary. You can pass the string array as a input to the query (as long as the string values represent numbers).

You can get what you need in one line:

Candidate.find_all_by_id(params[`candidate`])

Which is same as:

Candidate.find(:all, :conditions => {:id => params[`candidate`]})

Which is same as:

Candidate.find(:all, :conditions => ["id IN (?)",params[`candidate`]])

Your original attempt did not work because you did not put brackets after the IN clause.

KandadaBoggu