将参数转换为整数数组的Ruby on Rails操作

5

我正在使用get方法发送数据,并且需要将其放入一个int数组中以便在查找中使用。 以下是我的代码:

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

我的网址看起来像这样
http://localhost:3000/export/candidate?candidate[]=3&candidate[]=4&commit=Export

如果有所不同,我正在使用它来查找。
@candidate = Candidate.find(:all, :conditions => ["candidates.id IN ?", @found]) 

但目前它并没有将其放入真正的数组中,因为我遇到了这个错误

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)

数组周围缺少括号
谢谢,早上好!
Alex
2个回答

16

只需要在你的“?”周围加上括号即可。

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

另外,你的第一段代码可以简化为:

@found = params['candidate'].map(&:to_i)

谢谢你的帮助!这个符号 &: 是什么意思? - Alex
1
这是一种简单的传递块的方式,它只是在传递到块中的参数上调用给定方法。在http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html上有一个很好的解释。 - Gareth
似乎.map非常有用。 - Vinnyq12

1

你所做的整个转换是不必要的。只要字符串值表示数字,你可以将字符串数组作为查询的输入传递。

你可以在一行代码中得到你需要的结果:

Candidate.find_all_by_id(params[`candidate`])

这与以下内容相同:

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

这与以下代码相同:

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

你原本的尝试没有成功是因为你在 IN 子句后面没有加括号。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接