首页 > 解决方案 > How do I like a user model with this setup?

问题描述

I have setup a polymorphic liking in my my app where a user can like other models e.g book, chapter, article... Now I tried to take it a little further by allowing a user like another user but I'm running to this error:

Validation failed: User must exist

pointing to

likes.where(item: item).create!

This is my initial setup for liking other models excluding the user model

like.rb

belongs_to :user
belongs_to :item, polymorphic: true

user.rb

has_many :likes, dependent: :destroy

def toggle_like!(item)
    if like = likes.where(item: item).first
      like.destroy
    else
      likes.where(item: item).create!
    end
end

def likes?(item)
    likes.where(item: item).exists?
end

likes_controller.rb

class LikesController < ApplicationController
    before_action :authenticate_user!

    def toggle
        if params[:book_id]
            item = Book.friendly.find(params[:book_id])
        elsif params[:user_id]
            item = User.find_by(username: params[:username])
        end

        current_user.toggle_like!(item)
        redirect_back(fallback_location: root_path)
    end
end

book.rb

has_many :likes, as: :item, dependent: :destroy

For a user to like another user, i adjusted the user.rb from

has_many :likes

to

has_many :likes, as: :item, dependent: :destroy

This is when I get the error

Validation failed: User must exist

pointing to

likes.where(item: item).create!

in the user.rb

标签: ruby-on-railsruby

解决方案


保留has_many :likes, dependent: :destroy并添加has_many :received_likes, as: :item, class_name: "Like", dependent: :destroy. 我认为这将解决它。因为当您放置User has_many: :likes, as: :item和删除时User has_many: :likes,这意味着该关联Like belongs_to :user是片面的。


推荐阅读