I have implemented a favoriting system for my rails app by following this great article.
Here is my set up:
favorite.rb
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :favorited, polymorphic: true
end
project.rb
class Project < ActiveRecord::Base
belongs_to :user
has_many :favorites, as: :favorited
has_many :fans, through: :favorites, source: :user
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
Here is the problem.
I had some favorited projects.
I used Project.delete_all
to delete my projects while certain projects were still "favorited" but now I get an error:
ActionView::Template::Error (undefined method `favorite_projects' for nil:NilClass):
I'm sure If I had "unfavorited" all those projects before deleting them, this error would not come up.
Does anyone have an idea on how to fix this?
Aucun commentaire:
Enregistrer un commentaire