我有一个不是特定于表的SQL查询,我不知道如何使用Ruby On Rails处理它。
这是我的SQL查询(你不需要理解它):
SELECT type, actor_id, events.created_at, photo_id, photos.user_id FROM (SELECT 'comment' AS type, user_id AS actor_id, created_at, photo_id FROM comments UNION SELECT 'classification' AS type, user_id AS actor_id, created_at, photo_id FROM classifications) AS events INNER JOIN photos ON photo_id = photos.id WHERE user_id = #{@user.id} ORDER BY created_at DESC LIMIT 9
我尝试创建模型并使用find_by_sql:
class RecentActivity ActiveRecord::Base
attr_accessor :type, :actor_id, :created_at, :photo_id, :user_id
end
我明白了:
Mysql::Error: Table 'mysite_development.recent_activities' doesn't exist: SHOW FIELDS FROM `recent_activities`
如何避免此消息?有没有替代方案?
答案 0 :(得分:36)
您可以直接从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}
答案 1 :(得分:7)
您还可以获取ActiveRecord连接并致电select_all:
ActiveRecord::Base.connection.select_all('select * from foo').each do |e|
puts e.inspect
end
答案 2 :(得分:0)
如果要创建不支持数据库的类(模型),则不需要声明它们是从ActiveRecord继承的。
做
class RecentActivity
而不是
class RecentActivity < ActiveRecord::Base
话虽如此,获取有关您正在尝试做的事情的更多信息仍然可能有所帮助:例如,如果您希望在文章等多个不同的内容上添加“评论”或“图片”等内容,或者有人在同一个应用程序中使用个人资料或博客文章,我建议您查看PolyMorphic Associations。