我已经按照 this great article 为我的 Rails 应用程序实现了收藏系统.
这是我的设置:
最喜欢的.rb
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :favorited, polymorphic: true
end
项目.rb
class Project < ActiveRecord::Base
belongs_to :user
has_many :favorites, as: :favorited
has_many :fans, through: :favorites, source: :user
用户.rb
class User < ActiveRecord::Base
has_many :listings
has_many :projects
has_many :favorites
has_many :favorite_listings, through: :favorites, source: :favorited, source_type: 'Listing'
has_many :favorite_projects, through: :favorites, source: :favorited, source_type: 'Project'
favorite_projects_controller.rb
class FavoriteProjectsController < ApplicationController
before_action :set_project
# before_action :correct_user
# before_action :authenticate_user!
def create
if Favorite.create(favorited: @project, user: current_user)
redirect_to @project, notice: 'Project has been favorited'
else
redirect_to @project, alert: 'Something went wrong...*sad panda*'
end
end
def destroy
Favorite.where(favorited_id: @project.id, user_id: current_user.id).first.destroy
redirect_to @project, notice: 'Project is no longer in favorites'
end
private
def set_project
@project = Project.find(params[:project_id] || params[:id])
end
end
问题就在这里。
我有一些最喜欢的项目。
我使用 Project.delete_all
删除了我的项目,而某些项目仍处于“收藏夹”状态,但现在出现错误:
ActionView::Template::Error (undefined method `favorite_projects' for nil:NilClass):
我确信如果我在删除所有这些项目之前“取消收藏”它们,则不会出现此错误。
有人知道如何解决这个问题吗?
最佳答案
您需要设置依赖选项。
has_many :favorites, as: :favorited, dependent: :destroy
在任何将对象保留在数据库中没有意义的关联上设置此项。
您无需在 through
has_many 关联上设置它。
关于ruby-on-rails - 删除多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42677529/