没有对应表的自定义SQL查询

我有一个不是特定于表的SQL查询,我不知道如何使用Ruby On Rails处理它。

这是我的SQL查询(你不需要理解它):

  SELECT类型,actor_id,events.created_at,photo_id,photos.user_id FROM 
 (SELECT'comment'AS类型,user_id AS actor_id,created_at,photo_id FROM comments
联盟
 SELECT'分类'AS类型,user_id AS actor_id,created_at,photo_id FROM分类) 
 AS事件
 INNER JOIN照片ON photo_id = photos.id
 WHERE user_id = #{@user.id}
 ORDER BY created_at DESC
限制9 

我试图创建一个模型并使用find_by_sql:

class RecentActivity ActiveRecord::Base attr_accessor :type, :actor_id, :created_at, :photo_id, :user_id end 

我明白了:

  Mysql ::错误:表'mysite_development.recent_activities'不存在:显示来自`recent_activities的字段 

我该如何避免这条消息? 有没有替代解决方案?

您可以直接从ActiveRecord :: Base获取数据库连接,但它没有扩展AR :: Base那么有用,因为像sanitize_sql这样的有用方法受到保护。

 class ComplexQueries < ActiveRecord::Base def self.my_query # Notice how you can, and should, still sanitize params here. self.connection.execute(sanitize_sql(["select * from foo limit ?", 10])) end end results = ComplexQueries.my_query results.each_hash{|h| puts h.inspect} 

您还可以获取ActiveRecord连接并调用select_all :

 ActiveRecord::Base.connection.select_all('select * from foo').each do |e| puts e.inspect end 

如果要创建不支持数据库的类(模型),则不需要声明它们是从ActiveRecordinheritance的。

 class RecentActivity 

代替

 class RecentActivity < ActiveRecord::Base 

话虽如此,获取有关您正在尝试做的事情的更多信息仍然可能有所帮助:例如,如果您希望在诸如文章或某些个人资料等多个不同的内容上使用“评论”或“图片”之类的内容blogpost都在同一个应用程序中,我建议查看PolyMorphic Associations 。