当评论可以属于另一个可评论时,如何查询多态注释?

时间:2012-10-31 20:53:19

标签: ruby-on-rails-3.1 comments polymorphism

所以我正在尝试对多态模型进行相对高级的查询。我有以下型号:

class Project < ActiveRecord::Base
  has_many :project_stakeholders, :dependent => :destroy
  has_many :features, :dependent => :destroy
  has_many :iterations, :dependent => :destroy
  has_many :comments, :as => :commentable, :dependent => :destroy
end

class ProjectStakeholder < ActiveRecord::Base
  belongs_to :project
  has_many :comments, :as => :commentable, :dependent => :destroy
end

class Feature < ActiveRecord::Base
  belongs_to :project
  has_many :comments, :as => :commentable, :dependent => :destroy
end

class Iteration < ActiveRecord::Base
  belongs_to :project
  has_many :comments, :as => :commentable, :dependent => :destroy
end

class User < ActiveRecord::Base
  has_many :comments, :dependent => :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
  belongs_to :created_by, :class_name => 'User'
end

我正在尝试查找current_user对特定项目的评论(project.comments,project.features.comments,project.iterations.comments,project.project_stakeholder.comments),并按created_at降序排序。

我想出的最好的是:

Class Project < ActiveRecord::Base
  def all_comments_for_user(user)
    Comment.where(:created_by_id => user.id).select { |c| c.commentable.attributes.has_key?('project_id') }.select { |c| c.commentable.project == self } | comments.where(:created_by_id => user)
  end
end

但这并没有解决降序的create_at序列。

1 个答案:

答案 0 :(得分:0)

Class Project < ActiveRecord::Base
  def all_comments_for_user(user)
    Comment.where(:created_by_id => user.id).order('created_at DESC').select { |c| c.commentable.attributes.has_key?('project_id') }.select { |c| c.commentable.project == self } | comments.where(:created_by_id => user)
  end
end

这有用吗?我刚刚添加了订单('created_at DESC')