我正在尝试查询字符串数组。 me_topics_users表是Rails自动生成的表,所以要查询它,我必须使用自定义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 :(得分:0)
您可以使用ActiveRecord #find
来使用字符串替换技术find_by_sql(["SELECT * FROM `me_topics_users` WHERE (me_topic_id IN (?))",@topics.join(', ')])
答案 1 :(得分:0)
ActiveRecord::Base.connection.execute("SELECT * FROM `me_topics_users` WHERE (me_topic_id IN ('#{@topics.join("', '")}') )")