Rails方法使查找连接表(使用.find方法)

时间:2011-12-28 14:54:40

标签: ruby ruby-on-rails-3 orm model

我有以下表格:

UserAction:
type_action:string
entity_id:int
日期:日期时间
user_id:int(引用用户)

问题:
text:string
user_id:int(引用用户)
回答:tinyint

EntityTracker
type_track:string
entity_id:int
动作:字符串
日期:日期时间

我需要知道满足这些条件的EntityTracker(alias et)中有多少(计数)记录:
- action ='ANSWERED'
- type_track ='问题'
- 日期>比(UserAction(别名ua)中的记录日期与ua.entity_id = et.entity_id和ua.type_action = et.type_track)
- entity_id符合条件:id = et.entity_id的问题有user_id = params [:user_id]


所以我必须加入Question和UserAction。
有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

也许是这样的:

EntityTracker.find(:all,
                   :from => 'entity_trackers et',
                   :select => 'COUNT(et.id) AS count',
                   :conditions => ['et.action = ? AND
                                    et.type_track = ? AND
                                    et.date > (SELECT MAX(ua.date)
                                               FROM user_actions ua
                                               WHERE ua.entity_id=et.entity_id AND
                                                     ua.type_action=et.type_track) AND
                                    EXISTS (SELECT questions.id
                                            FROM questions
                                            WHERE questions.id=et.entity_id AND
                                                  questions.user_id=?)',
                                   'ANSWERED', 'QUESTION', user_id])