在SQL文的查询条件中经常会用得到关键字in,例如:
SELECT * FROM accounts WHERE nick_name = 'nicknm' AND id IN ("1","2");
此时如果利用Rails的find方法,代码如下所示:
require "rubygems" require "active_record" module ActiveRecord class Base def self.each_cons(n) offset = 0 loop do size = yield(offset) break if size < n offset += n end end end end ActiveRecord::Base.establish_connection( :adapter => 'mysql', :host => 'localhost', :database => 'myapp_development', :username => 'my', :password => '123' ) class Account < ActiveRecord::Base establish_connection( :adapter => 'mysql', :host => 'localhost', :database => 'myauth_development', :username => 'my', :password => '123' ) end #condns 是个数组 condns = [] condns << "1" condns << "2" #非常值得注意的是:此时传给in(即第二个?)的参数一定要是数组类型的, #否则返回的不是想要的结果。 #举例说明:如果将condns设置成字符串类型→"1,2",那么下述find方法解析完的 #SQL是SELECT * FROM accounts WHERE nick_name = 'nicknm' AND id #IN ("1,2"); #而我们期待的结果应该是: #SELECT * FROM accounts WHERE nick_name = 'nicknm' AND id IN #("1","2"); accounts = Account.find(:all, :conditions => ["nick_name = ? and id in (?)", "nicknm", condns], :order => 'id asc', :limit => 1000)