我正在嘗試查詢字符串數組。 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
這是一個壞主意。現在它可能正常工作,但只需等到有人用[SQL注入攻擊](http://en.wikipedia.org/wiki/SQL_injection)擊中你即可。 – 2011-09-26 14:52:18
@BrianDonovan那麼一點小智慧呢! :)我也試圖避免這樣做......我在Rails之外使用ActiveRecord,而sanitize_sql有點棘手的漏洞 – RGB 2013-11-22 15:45:32
@RGB你究竟在做什麼?我可以幫你解決問題。儘管將我鏈接到一個新的Stackoverflow問題。我想解開你的情況以外的評論線程。 – Trip 2013-11-22 16:08:43