intro_rails

创建 Likeable

migration.rb

class CreateLikes < ActiveRecord::Migration
  def change
    create_table :likes do |t|
      t.belongs_to :user, index: true
      t.belongs_to :likeable, polymorphic: true, index: true

      t.timestamps
    end
  end
end

model like.rb

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :likeable, polymorphic: true, counter_cache: true

  validates :user, :likeable, presence: true
end

concerns/likeable.rb

module Likeable
  extend ActiveSupport::Concern

  included do
    has_many :likes, as: 'likeable', dependent: :delete_all
  end

  def liked_by?(user)
    likes.where(user: user).exists?
  end
end

其他需要添加喜欢功能的模型添加include Likeable

routes.rb

  concern :likeable do
    resource :like, only: [:create, :destroy]
  end

  # 其他需要的 like 功能的
  resources :topics, concerns: :likeable

likes_controller.rb

class LikesController < ApplicationController
  before_action :find_likeable

  def create
    @likeable.likes.find_or_create_by user: current_user
  end

  def destroy
    @likeable.likes.where(user: current_user).destroy_all
  end

  private

  def find_likeable
    resource, id = request.path.split('/')[1, 2]
    @likeable = resource.singularize.classify.constantize.find(id)
  end
end