2

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

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

我正在尝试查找特定项目(project.comments、project.features.comments、project.iterations.comments、project.project_stakeholder.comments)的 current_user 评论,并按 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 序列。

4

1 回答 1

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

这行得通吗?我刚刚添加了 order('created_at DESC')

于 2012-11-01T14:09:07.097 回答