2011-02-22 60 views
1

我有一个模型事件的外键的连接模型。Ruby/Rails - 查找模型中大多数实例的外键

加入的模型被称为目标。我试图找到适当的查找条件来确定哪个event_id在目标加入模型中具有最多的实例。 Essenially哪个外键id在连接模型中的条目最多。

有没有办法做到这一点?

Goal.where(:event.id => ???????).first 
+0

你可以给我们你有关模型的代码吗? – corroded 2011-02-22 19:43:44

回答

1

无法拿出一个更优雅的解决方案,但尝试这个办法:

results = Goal.connection.select_all('SELECT COUNT(*) as amount, event_id FROM goals GROUP BY event_id ORDER BY amount DESC LIMIT 0, xx') 
raise results.inspect 

如果你只是想一个最事项标识与您还可以使用大部分条目:

event_id = Goal.connection.select_one('SELECT COUNT(*) as amount, event_id FROM goals GROUP BY event_id ORDER BY amount DESC LIMIT 1').first 
0

如果您已正确设置模型,则应该可以执行此操作(如果情况并非如此:正确设置模型):

if Event.all.length == 0 
    return 
end 

eventMax = Event.first 
Event.all.each do |e| 
    eventMax = e.goals.length>eventMax.goals.length?e:eventMax 
end 

#output or do whatever with your newly found event 
puts eventMax.to_json 

丹尼的解决方案并不是很好。

你永远不应该(或者至少很少)不得不自己在rails中编写sql。

+0

如果我正确地理解了这个问题,那么你想要的是最具目标的事件。 – Automatico 2012-07-07 13:12:34