這似乎並不奏效:你如何在(?)調用中執行SQL查找?
@zip = %w[07005, 07034, 07035]
CardSignup.find(:all, :conditions => ["zip_code IN (?)", @zip])
=> [ ]
但是,如果我做一個簡單的find_by與第二郵政編碼,它返回一個結果:
CardSignup.find_by_zip_code("07034")
=> Object<x..
我在做什麼錯?
這似乎並不奏效:你如何在(?)調用中執行SQL查找?
@zip = %w[07005, 07034, 07035]
CardSignup.find(:all, :conditions => ["zip_code IN (?)", @zip])
=> [ ]
但是,如果我做一個簡單的find_by與第二郵政編碼,它返回一個結果:
CardSignup.find_by_zip_code("07034")
=> Object<x..
我在做什麼錯?
你執行數組的不正確。你有它此刻的方式逗號是每個數組對象的一部分:
>> %w[07005, 07034, 07035]
=> ["07005,", "07034,", "07035"]
您應該刪除逗號實現這一點:
>> %w{07005 07034 07035}
=> ["07005", "07034", "07035"]
或:
>> [07005, 07034, 07035]
=> [07005, 07034, 07035]
所以全部實施是:
@zip = %w{07005 07034 07035}
CardSignup.find(:all, :conditions => ["zip_code IN (?)", @zip])
=> [Object<x..
嘗試:
CardSignup.find_by_zip_code(@zip)
編輯(從評論):
How to select where ID in Array Rails ActiveRecord without exception
@zip = ["07005", "07034", "07035"]
CardSignup.find(:all, :conditions => ["zip_code IN (?)", @zip])
CardSignup.find_all_by_zip_code(["07005", "07034", "07035"])
Don't use comma in %w[07005, 07034, 07035]
Just use %w[07005 07034 07035]
如何修改該語法以在其中包含「OR」語句?我正在尋找的最終結果是使用Rails/SQL語法而不是Rails幫助程序。 – Trip 2011-04-04 11:42:31
你正在使用的Rails版本是? – 2011-04-04 11:44:33
http://stackoverflow.com/questions/1441791/how-to-select-where-id-in-array-rails-activerecord-without-exception – 2011-04-04 11:45:02