简体   繁体   English

Rails为同一模型的多态关联和has_many

[英]Rails polymorphic association and has_many for the same model

I have the Comment model which belongs to some other models like Post, Page etc and has_one (or belongs_to?) User model. 我有Comment模型,它属于其他一些模型,如Post,Page等和has_one(或belongs_to?)用户模型。 But I need the User to be commentable too, so User has to have many Comments from other Users (this is polymorphic :commentable association) and he has to have his own Comments, written by him. 但是我也需要用户可以评论,所以用户必须有很多来自其他用户的评论(这是多态的:可评论的关联),他必须有自己的评论,由他撰写。 What is the best way to make an association like this? 建立像这样的协会的最佳方式是什么? How can I read and create Comments for User in a controller if User has two different associations with Comments? 如果用户与评论有两种不同的关联,如何在控制器中读取和创建用户评论? Now I do this and it's not right I guess: 现在我这样做,这是不对的我想:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :comments, as: :commentable
  has_many :comments
end

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

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :content
      t.references :commentable, polymorphic: true, index: true
      t.belongs_to :user
      t.timestamps null: false
    end
  end
end

You'll want to use another name for that association. 您将要为该关联使用其他名称。

has_many :comments, as: :commentable
has_many :commented_on, class_name: 'Comment' # you might also need foreign_key: 'from_user_id'.

See has_many 's documentation online . 在线查看has_many的文档

The foreign_key should not be needed in your case, but I'm pointing it out Just In Case™. 在你的情况下不应该使用foreign_key ,但我指出Just In Case™。 Rails will guess "{class_lowercase}_id" by default (so user_id in a class named User). 默认情况下,Rails会猜测“{class_lowercase} _id”(所以在名为User的类中为user_id )。

Then you can access both associations (The class_name is explicitly needed because Rails can't find Comment from commented_on ). 然后您可以访问这两个关联(明确需要class_name ,因为Rails无法从commented_on找到Comment )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM