0

ユーザーが投稿にコメントできるモデルとモデルがあるとしますUser。次のようなポリモーフィックな関係を設定しました。PostComment

class User < ActiveRecord::Base
  has_many :comments
end

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

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

ユーザーが別のユーザーにコメントできるようにしたいのですが、問題が発生しています。に沿って何かできると思っていたのですが、うまくいきhas_many :notes, :as_commentableません。

何かアドバイス?

4

1 に答える 1

0

これをユーザーモデルに追加する必要があります。

class User < ActiveRecord::Base
  has_many :comments
  has_many :comments_from_other_users, :as => :commentable, :class_name => 'Comment'
end

関係の名前がひどいことは知っていますが、それは簡単に理解でき、必要に応じて変更できます。

だからあなたは後にこれを持っているべきです:

current_user.comments.each do |comment|
  comment.user # author of the comment
  comment.commentable # object that you posted the comment on (GroupRun for instance)
end
current_user.comments_from_other_users.each do |comment|
  comment.user # author of the comment
  comment.commentable # user on which the comment is posted (should be equal here to current_user)
end
于 2013-02-19T14:42:14.043 に答える