Rails Query 选择最新记录的最佳方法
我有这个方法,我希望我从跟踪所有用户的模型 UserActivity
中获取相应 user_id
的最新 activity_id
活动,并从中获取另一个模型 Activity
的 Activity_id 的 description
。 该函数工作正常,但有时会抛出“无法找到 Activity_id”的错误。可能有更好的方法来实现这个或者我在这里做错了什么吗?
def last_activity(date, user_id)
active_id = UserActivity.find(:all, :conditions => ["Date(updated_at) <= ? and user_id = ?", date, user_id]).last.activity_id
text = Activity.find(active_id).description
end
模型UserActivity
的架构如下:
请帮助我解决此问题。谢谢 !!
Ruby 版本 1.8.7、Rails 2.1.2
I have this method which I want me to fetch the most recent activity_id
for the corresponding user_id
from the model UserActivity
that keeps track of all the user activities and from that get the description
of the activity_id from another model Activity
.
The function works fine but at times throws bugs as "Not able to find activity_id". May be there could be a better way to implement this or Am I doing something wrong here ?
def last_activity(date, user_id)
active_id = UserActivity.find(:all, :conditions => ["Date(updated_at) <= ? and user_id = ?", date, user_id]).last.activity_id
text = Activity.find(active_id).description
end
The Schema of the model UserActivity
is as follows :
Please help me get this fixed. Thanks !!
Ruby version 1.8.7, Rails 2.1.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您有以下模型
获取当前用户的最后一个活动
这依赖于具有最大 id 的 UserActivity 对象是最新活动的事实。
如果创建后更新
UserActivity
,则必须更改关联的order
子句,即Assuming you have following models
To get the current user's last activity
This relies on the fact that UserActivity object with the max id is the latest activity.
If you update the
UserActivity
after creation, you have to change theorder
clause of the association, i.e.查询未找到任何匹配项,或者某些记录的 Activity_id 列可能具有
null
值,以下代码应该有效Either the query is not finding any match or some records might be having
null
values for activity_id column, following code should work