1

belongs_toコメントを User と Page の両方に関連付ける場合、Railsの関連付けにはかなり戸惑います。コメントをユーザーとページの両方に関連付ける方法はありますか? 次の例を見てください(私にはうまくいきませんが、実証する簡単な例です):

# The basic idea is that I would like to have User show comments from the user
# on all pages, and Page show all the comments for the page.
# User.find_by_email('email@domain.com').comments # Show comments on pages.
# Page.find_by_slug('my-slug').comments # Show comments on the page.

class Comments
  include Mongoid::Document and include Mongoid::Timestamps
  include MyApp::Mongoid::Patches::DefaultType

  belongs_to :page
  belongs_to :user

  field :content, type: String
end

class Page
  include Mongoid::Document and include Mongoid::Timestamps
  include MyApp::Mongoid::Patches::DefaultType

  belongs_to :user
  has_many :comments

  field :type, type: String, default: :post
  field :slug, type: String
  field :title, type: String
  field :content, type: String
  field :tags, type: Array, default: :user

  private
  # .....
end

class User
  include Mongoid::Document and include Mongoid::Timestamps
  include MyApp::Mongoid::Patches::DefaultType

  embeds_one :provider
  has_many :pages
  has_many :comments # But only from Pages not on the user.

  field :email, type: String
  field :name, type: String
  field :role, type: Symbol, default: :user
end
4

1 に答える 1

0

ここで探しているのは、多態的な関連付けのようです。ポリモーフィック アソシエーションの公式 Rails ガイドのリンクを確認してください。簡単に言うと、次のようになります。

class Comments
  belongs_to :commentable, :polymorphic => true
end

class User
  has_many :comments, :as => :commentable
end

class Page
  has_many :comments, :as => :commentable
end

ここで、コメント テーブルに commentable_type(string) と commentable_id(integer) の 2 つのフィールドを追加します。

これで、ユーザーとページの両方にコメントを付けることができます。

コメントがコメントオブジェクトの場合、comment.commentable を使用してそのコメントのユーザー/ページを取得できます

于 2012-08-03T15:13:22.043 に答える