简体   繁体   English

ruby rails将params转换为int数组

[英]ruby rails converting params to int array

I am sending data via get and I need to put it into a int array to be used in a find. 我通过get发送数据,我需要将它放入一个int数组中以便在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 亚历克斯

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)

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. 您的原始尝试不起作用,因为您没有在IN子句后放置括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM