重构一段时间后创建的父级子级的查找
我试图找到在日期时间之后创建的任何不是当前用户发出的评论。
起初我这样做了..
current_user.comments.find(:all, :conditions=>["created_at > ? AND user_id != ?",
current_user.last_checked_mail, current_user])
但这里的问题是,因为它从用户模型开始,所以它只能找到该用户专门发表的评论。
因此,我开始搜索与用户相关的所有评论,以及这些评论的子项,只要它们的 user_id 不是 current_user
Comment.find(:all, :conditions => ["user_id = ?", current_user]).select { |c|
c.comments.find(:all, :conditions => ["user_id != ?", current_user])
}
但似乎仍然绘制与 current_user 相关的每一条评论,而不是它们的子项。
我的评论模型:
belongs_to :commentable, :polymorphic => true
has_many :comments, :as => :commentable
I am trying to find any comments created after a datetime that were not made by the current user.
At first I did this..
current_user.comments.find(:all, :conditions=>["created_at > ? AND user_id != ?",
current_user.last_checked_mail, current_user])
but the problem here was that because it begins with the user model, its only finding comments exclusively made by that user.
So instead, I began searching for all comments associated with the user, and those comments children so long as their user_id is not the current_user
Comment.find(:all, :conditions => ["user_id = ?", current_user]).select { |c|
c.comments.find(:all, :conditions => ["user_id != ?", current_user])
}
But it seems that still draws every single comment related to the current_user, and not their children.
My Comment Model :
belongs_to :commentable, :polymorphic => true
has_many :comments, :as => :commentable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么你的评论模型中有父母关系吗?用那个!
附言。这是针对 Rails 3 的。
So you have a parent relation in your comment model? Use that!
PS. This is for Rails 3.
尝试:
Try:
试试这个:
更好的解决方案是在
Comment
模型上创建一个named_scope。现在您可以通过以下方式获取其他评论:
编辑 1
基于多态关联的更新答案:
现在您可以获得其他评论:
Try this:
Better solution is to create a named_scope on the
Comment
model.Now you can get others comments as:
Edit 1
Updated answer based for Polymorphic associations:
Now you can get others comments as: