I have been learning rails and building blogs site and introduced the like model for posts.
I have created a like model for liking a blog post using polymorphic association with user user_id
and blogs blog_id
.
and i want to have a like button for a comments on each blog post, and i don't know which way to do is better
- can i have a
comment_id
on the same like model , will it be correct or may break polymorphic association
or - Should i make a totally different like model for comments with
user_id
andcomment_id
as a foreign key
CodePudding user response:
You should use Polymorphic Association here. But I notice that you have the wrong understanding of Polymorphic Association in the above explanation because you are referencing Blog
& Comment
via blog_id
& comment_id
respectively in the Like
model instead of referencing those through likeable
(i.e., likeable_id
& likeable_type
). Follow the below steps for better understanding.
- Generate
Like
model
rails g model Like user:references likeable:references{polymorphic}
Like
model migration should look like this
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
- Like model
class Like < ApplicationRecord
belongs_to :user
belongs_to :likeable, polymorphic: true
end
- Blog model
class Blog < ApplicationRecord
has_many :likes, as: :likeable
end
- Comment model
class Comment < ApplicationRecord
has_many :likes, as: :likeable
end
- Table entries of
Like
model should look similar to this
=> #<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>>