class Reaction < ApplicationRecord
belongs_to :reactable, polymorphic: true
validates :emoji, presence: true, format: { with: /\p{Emoji}/, message: "must be a valid emoji" }
end
class Post < ApplicationRecord
has_many :reactions, as: :reactable, dependent: :destroy
end
class CreateReactions < ActiveRecord::Migration[7.0]
def change
create_table :reactions do |t|
t.references :reactable, polymorphic: true, null: false
t.string :emoji, null: false
t.timestamps
end
end
end
This snippet introduces a polymorphic emoji reaction system in Rails, allowing models like Post
(or any other) to receive emoji reactions. The Reaction
model supports different reactable types via polymorphic: true
. A simple emoji regex ensures valid reactions. This setup makes it easy to add likes, claps, fire emojis, or even 🦄 reactions to any model in your app!
Martin Sojka, Maker of CodeSnips