Search code examples
ruby-on-railsformsacts-as-audited

Audited: undefined method `associated' for nil:NilClass


So I have a Entry model with a column called created_by which I would like to default to the first User who created the entry. I installed audited and in my Entry model I have:

belongs_to :user
audited :associated_with => :user

Similarly in my User model I have the following statements:

has_many :entries     
has_associated_audits

In my entries form, I was trying to create a hidden_field in which I was trying to set created_by to be equal to the the associated user of the first audit on the entry. However I'm getting this error, when I try to load the form view:

undefined method `associated' for nil:NilClass

Here is the code in the view:

 .field
   = f.label :created_by
 %br
   = f.hidden_field :created_by, value: @entry.audits.first.associated

And here is the code in the entries_controller where I set @entry in the view:

  def new
    @entry = Entry.new
    authorize! :create, @entry

    @project = Project.find(params[:project_id])
    @entry.project_id = @project.id
    authorize! :update, :read, @project
  end

I realize that, intuitively, it doesn't make much sense to call @entry.audits in the event of creating a new audit, since it has not yet been saved. Should I set the value of @entry.created_by after I call @entry.save in the create method of the controller? Not really sure about what is the most practical approach to take here.

Thanks,

Micha'el.


Solution

  • What I'd do is remove the created_by hidden field from the form (that is easily intercepted), and instead set from within the controller before the entry is saved using current_user (or alternative) to access the user creating the entry.

    def create_entry
      @entry.created_by = current_user
      @entry.save
    end
    

    I wouldn't consider it important to assign the created_by user after the audit has been saved via @entry.audits.first.associated because those audits should be associated to the same current_user. If that isn't the case, you have bigger problems on your hands.