5

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&candidate[]=4&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 Answers 2

16

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help! what does this mean &: ?
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 pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html
it seems .map is quite useful
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.