0

I have a problem with an audited gem. It's two problems in one. I installed and configured the audited gem in my application, but when I delete the database and run migrate and seed again, the user_id and user_type fields in the database are NULL in addition, when I register a user through devise sign_up (new_registration_path) the user_id and user_type are also registered as NULL in the database, which causes an error, as can be seen in the image or here:

enter image description here

undefined method `name' for nil:NilClass

The error line is this:

<%= f.select :user_name_cont, Audity.all.map { |u| [u.user.name] }.uniq, include_blank: true %>

enter image description here

I already put in my Audity model a belongs_to optional: true, but still the error continues.

My application is on my github: https://github.com/eltonsantos/auth-rails

How do I resolve this error? The solution I think is when running the seed or registering a new user, run an after_save or an after_create putting some default id in the user_id field (maybe his own id), but I'm not sure if it's the best solution.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Elton Santos
  • 571
  • 6
  • 32
  • I think you need to update the user creation method to initialize those fields. Can you share the code that initializes a user? – JackHacks Jan 30 '22 at 23:38
  • I think you need to update your seed file to provide the user details. There is no way for audited to set a user for the records when you seed the database. In a running application, however, the user will automatically be set as long as there is a `current_user` method which returns the user. – Ankit Jan 31 '22 at 12:38
  • 1
    @JackHacks my controller: https://github.com/eltonsantos/auth-rails/blob/master/app/controllers/users_controller.rb – Elton Santos Feb 01 '22 at 03:56

1 Answers1

1

I pulled your rails app and ran the database seed. The error disappeared for me after fixing a typo in your user.rb file.

class User < ApplicationRecord

  audited
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  enum role: { superadmin: 0, auditor: 1, manager: 2, registred: 3 }

  has_many :cars

  has_one_attached :avatar # removed a comma here

end

Let me know if that resolves the issue for you also.

Boa sorte!

JackHacks
  • 262
  • 1
  • 12