1

コメントには通常のポリモーフィックな関連付けがあります。

class Book < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
    belongs_to :commentable, :polymorphic => true
end

コメントのcreated_atタイムスタンプに基づいてBook.recently_commentedとArticle.recently_commentedを定義できるようにしたいと思います。今、私はネストされたselectでこれを行うためのかなり醜いfind_by_SQLクエリを見ています。SQLに頼らずにRailsでそれを行うためのより良い方法があるに違いないようです。

何か案は?ありがとう。

その価値については、SQLを次に示します。

select * from 
    (select books.*,comments.created_at as comment_date 
    from books inner join comments on books.id = comments.commentable_id 
    where comments.commentable_type='Book' order by comment_date desc) as p 
group by id order by null;
4

2 に答える 2

2

コメントしているオブジェクトにフィールドを追加するのが最善の場合もあります。多分日時タイプのcommented_atフィールドのように。オブジェクトにコメントが付けられたら、その値を更新するだけです。

SQLを使用してそれを行うことは可能ですが、commented_atメソッドの方がはるかにスケーラブルであることがわかる場合があります。

于 2010-09-13T16:26:42.400 に答える
1

以前のメソッドの外観はわかりませんが、最初は次のようにします。

class Book < ActiveRecord::Base

  def self.recently_commented
    self.find(:all, 
              :include => :comments, 
              :conditions => ['comments.created_at > ?', 5.minutes.ago])
  end
end

これにより、過去5分間にコメントが作成されたすべての書籍が検索されます。(制限を追加することもできます)。

また、コードの繰り返しを避けるために、この機能の基本クラスを作成したいと思います。

class Commentable < ActiveRecord::Base
  self.abstract_class = true

  has_many :comments, :as => :commentable

  def self.recently_commented
    self.find(:all, 
              :include => :comments, 
              :conditions => ['comments.created_at > ?', Time.now - 5.minutes])
  end
end

class Book < Commentable
end

class Article < Commentable
end

また、これを実現するためにプラグインの使用を検討することもできます。例:acts_as_commentable

于 2010-09-13T16:45:36.120 に答える