ruby-on-rails - 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
解决方案
保留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
是片面的。
推荐阅读
- domain-driven-design - DDD:当工作单元不适用时,将存储库与文档数据库分离
- mysql - SQL 表达式中的语法错误 - 没有语法错误
- f# - 在 F# 中编写 UNIX 管道过滤器的惯用方法是什么?
- python - 根据另一个列表排序列表
- c# - .NET Core 中的零拷贝
- database - 使用 B+ 树插入项目的正确和标准方法是什么?
- python - Python 请求如何检索 cookie 以获取请求?
- python - 如何通过python中的管道读取二进制数据
- swift - 如何加载存储在我的资产目录中的纹理集?
- jasper-reports - 如何在碧玉报告中删除图表行中的空白行