[英]Rails polymorphic comments associate
尝试建立一个多态关联,其中“注释”可以属于“照片和用户”。 将对用户的评论视为“直接消息”。 但是我把用户关联弄得一团糟。
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
情况下检索所有Comment记录,而user.messages
应该在类型为User
且它们是主题的情况下检索所有Comment记录。
关系:
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
您是否已在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.