我有一些这样的模型:
class LogActivity < ActiveRecord::Base
has_many :call_logs
has_many :send_email_logs
has_many :send_sms_logs
...
end
class CallLog < ActiveRecord::Base
belongs_to :log_activity
end
class SendEmailLog < ActiveRecord::Base
belongs_to :log_activity
end
class SendSmsLog < ActiveRecord::Base
belongs_to :log_activity
end
现在,我希望在:call_logs
,:send_email_logs
,:send_sms_logs
中获得一条最新记录。我怎么能这样做?
答案 0 :(得分:1)
您可以尝试这样做 -
newest_call_log = LogActivity.call_logs.last
newest_sent_email_log = LogActivity.send_email_logs.last
newest_sent_sms_log = LogActivity.send_sms_logs.last
单个查询替代方法是执行此操作 -
newest_log = LogActivity.eager_load(:call_logs, :send_email_logs, :send_sms_logs).last
# The above will fire a query and fetch all the data you need, the below lines will segregate your data
newest_call_log = newest_log.call_logs.last
newest_sent_email_log = newest_log.send_email_logs.last
newest_sent_sms_log = newest_log.send_sms_logs.last
答案 1 :(得分:0)