Search code examples
ruby-on-railsrubydevisedestroy

Devise destroy user create bug in index page


I got a problem with my website in local when I delete an User with Devise on rails. The user is correctly deleted but now, when I go on the event index page, with normally a list of all the event, I got this message :

undefined method `pseudo' for nil:NilClass

It's because the deleted user has created event before being destroy, but now the application couldn't find the creator of the event etc...

I don't know how to fix it :
- How can I do if I want to keep the content he had created?
- should I delete all the content that the user delete in the same time?

I don't know if my problem is clear but I hope someone can help, thanks!


Solution

  • Rails gives you two options, from their guide:

    https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_one

    has_one :credit_card, dependent: :destroy  # destroys the associated credit card
    has_one :credit_card, dependent: :nullify  # updates the associated records foreign key value to NULL rather than destroying it
    

    As you can see from the comments, the first option, dependent: :destroy, will delete any associated content when the user is destroyed. dependent: :nullify will set the user_id for the content to null

    In your case, it appears a user has_many contents? Or has_one :content, either way the dependent: :destroy bit would be the same. To destroy the content when a user is destroyed:

    has_one :content, dependent: :destroy
    

    or

    has_many :contents, dependent: :destroy
    

    And to keep the content but set its owner to nil:

    has_one :content, dependent: :mullify