Cristiano
Cristiano

Reputation: 3199

Uninitialized constant error while deleting multiple connected records from database

I have the following database. After User registers to a site a new GalleryPhoto is created for him. He can have only one GalleryPhoto in which he can store multiple photos.

These are models:

class User < ActiveRecord::Base
  has_one :gallery_photos, :dependent => :delete
  has_many :photos, :through => :gallery_photos

  after_create :setup_gallery

  def setup_gallery
    GalleryPhoto.create(userId: self.id, name: self.email)
   end
end

class GalleryPhoto < ActiveRecord::Base
  belongs_to :user
  has_many :photos, :dependent => :delete_all
end

class Photo < ActiveRecord::Base
  belongs_to :gallery_photo
end

After I want to delete user:

def destroy
  User.find(params[:id]).destroy
end 

I receive the following error on that line:

NameError in UsersController#destroy
uninitialized constant User::GalleryPhotos

Gallery is created successfully after user registers and he can add images to it.

Thank you for your help!

Upvotes: 1

Views: 401

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 3427

modify this line

has_one :gallery_photos, :dependent => :delete
has_many :photos, :through => :gallery_photos

to

has_one :gallery_photo, :dependent => :delete
has_many :photos, :through => :gallery_photo

Upvotes: 2

Related Questions