Rails多态注释关联

时间:2018-07-09 02:25:24

标签: ruby-on-rails activerecord associations

试图建立一个多态关联,注释可以属于其中,例如“照片”和“用户”。将对用户的评论视为“直接消息”。但是我把用户关联弄得一团糟。

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

class Photo < ActiveRecord::Base
  has_many :comments, as: :commentable, dependent: :destroy
end

class User < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :messages, as: :commentable
end

这是不正确的。理想情况下,user.comments应该检索所有user_id == user.id的注释记录,而类似的user.messages应该检索类型为User并且它们是主题的所有Comment记录。

2 个答案:

答案 0 :(得分:1)

关系:

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

class Photo < ActiveRecord::Base
  has_many :comments, as: :commentable, dependent: :destroy
end

class User < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :messages, as: :commentable, class_name: 'Comment'
end

模式:

# Comments
 ...
 t.integer :user_id
 t.integer :commentable_id
 t.string :commentable_type
 ...

然后您可以调用:

@user.comments # Get all comments created by particular user
@user.messages # Get all comments where particular user is a subject

答案 1 :(得分:0)

您是否已将外键和类型列添加到comments表中?在迁移文件中:

  def change
    add_column :comments, :commentable_type, :integer
    add_column, :commentable_type, :string
    add_index :comments, [:commentable_type, :commentable_id]
  end

还要确保您拥有一个Message模型并具有关联性

class Message < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  belongs_to :commentable, polymorphic: true
end