喜欢 rails 中的评论

Liking a comment in rails

我一直在学习 rails 和构建博客网站,并为 post 引入了类似模型。 我创建了一个喜欢博客 post 的模型,使用与用户 user_id 和博客 blog_id 的多态关联。 我想在每个博客上有一个评论按钮 post,但我不知道哪种方式更好

  1. 我可以在同一个模型上有一个 comment_id 吗,它是正确的还是可能会破坏多态关联

  2. 我是否应该为使用 user_idcomment_id 作为外键的评论创建一个完全不同的 like 模型

你应该在这里使用多态关联。但是我注意到你在上面的解释中对多态关联的理解是错误的,因为你在 [=20= 中分别通过 blog_id & comment_id 引用了 Blog & Comment ] 模型而不是通过 likeable(即 likeable_idlikeable_type)引用那些模型。请按照以下步骤更好地理解。

  • 生成Like模型
rails g model Like user:references likeable:references{polymorphic}
  • Like 模型迁移应该是这样的
class CreateLikes < ActiveRecord::Migration[6.1]
  def change
    create_table :likes do |t|
      t.references :user, null: false, foreign_key: true
      t.references :likeable, polymorphic: true, null: false

      t.timestamps
    end
  end
end
  • 喜欢模特
class Like < ApplicationRecord
  belongs_to :user
  belongs_to :likeable, polymorphic: true
end
  • 博客模型
class Blog < ApplicationRecord
  has_many :likes, as: :likeable
end
  • 评论模型
class Comment < ApplicationRecord
  has_many :likes, as: :likeable
end
  • Table Like 模型的条目应该类似于此
 => #<Like:0x00# id: 1, user_id: 1, likeable_id: 1, likeable_type: "Blog", created_at: <timestamp>, updated_at: <timestamp>>

 => #<Like:0x00# id: 2, user_id: 1, likeable_id: 2, likeable_type: "Comment", created_at: <timestamp>, updated_at: <timestamp>>