だから私はポリモーフィックモデルで比較的高度なクエリを実行しようとしています。私は次のモデルを持っています:
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シーケンスには対応していません。