2011-04-04 69 views
0

我正在嘗試查詢字符串數組。 me_topics_users表是由Rails自動生成的表,所以爲了查詢它,我必須使用自定義SQL。如何在自定義SQL調用中添加自定義變量

@topics = self.distributions.map(&:me_topic).compact 
ActiveRecord::Base.find_by_sql("SELECT * FROM `me_topics_users` WHERE (me_topic_id IN (#{@topics.join(', ')}))") 

但這返回:

NoMethodError: undefined method `abstract_class?' for Object:Class 
from /Users/macuser/Sites/hq_channel/vendor/rails/activerecord/lib/active_record/base.rb:2207:in `class_of_active_record_descendant' 
from /Users/macuser/Sites/hq_channel/vendor/rails/ac 

什麼我錯在這裏做什麼?

更新了換人,但仍然得到了同樣的錯誤

ActiveRecord::Base.find_by_sql(["SELECT * FROM `me_topics_users` WHERE (me_topic_id IN (?))", @topics.join("', '")]) 

一個簡單的版本:

ActiveRecord::Base.connection.execute(["SELECT * FROM me_topics_users WHERE me_topic_id= ?", '4']) 

回報:

ActiveRecord::StatementInvalid: TypeError: wrong argument type Array (expected String): SELECT * FROM me_topics_users WHERE me_topic_id= ?4 
from /Users/macuser/Sites/hq_channel/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb:212:in `log' 
from /Users/macuser/Sites/hq_channel/vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:320:in `execute' 
from (irb):51 
from :0 

回答

0
ActiveRecord::Base.connection.execute("SELECT * FROM `me_topics_users` WHERE (me_topic_id IN ('#{@topics.join("', '")}'))") 
+3

這是一個壞主意。現在它可能正常工作,但只需等到有人用[SQL注入攻擊](http://en.wikipedia.org/wiki/SQL_injection)擊中你即可。 – 2011-09-26 14:52:18

+1

@BrianDonovan那麼一點小智慧呢! :)我也試圖避免這樣做......我在Rails之外使用ActiveRecord,而sanitize_sql有點棘手的漏洞 – RGB 2013-11-22 15:45:32

+0

@RGB你究竟在做什麼?我可以幫你解決問題。儘管將我鏈接到一個新的Stackoverflow問題。我想解開你的情況以外的評論線程。 – Trip 2013-11-22 16:08:43

0

你可以使用字符串替換技術爲你可以用ActiveRecord#查找

find_by_sql(["SELECT * FROM `me_topics_users` WHERE (me_topic_id IN (?))",@topics.join(', ')]) 
+0

不是。我試過很多方面,它似乎並沒有工作..'ActiveRecord :: Base.connection.execute([「SELECT * FROM?」,me_topics_users])' – Trip 2011-04-04 14:21:10

+0

另一個這樣的例子不工作,'ActiveRecord :: Base.connection.execute([「SELECT * FROM me_topics_users WHERE me_topic_id =?」,'4'])' – Trip 2011-04-04 14:22:41

+0

ok,find_by_sql只適用於activerecords。我認爲你有它的工作..我可以看到它在你的回答 – 2011-04-04 16:01:52

相關問題