current_user does not give me rails 5, Callbacks

0

Hello I want that when it is created automatically save the name and email, when the Callbacks is executed I get the following error, thanks.

reunion.rb

class Reunion < ApplicationRecord
  self.table_name = 'reuniones'
   belongs_to :planta
   belongs_to :centro_costo
   belongs_to :producto
   self.table_name = 'reuniones' 

  before_create :guardaremailsolitante
   def guardaremailsolitante
    self.emailsoli = User.find(current_user.id).email
    self.nombresoli = User.find(current_user.id).name
   end

 end
    
asked by MIGUEL ANGEL GIL RODRIGUEZ 17.10.2017 в 18:29
source

1 answer

1

The simplest thing (and in my opinion the best option) would be to include the current_user information as part of the attributes (ie parameters) that you use to create the Reunion object in your controller and remove the callback of the model; for example:

reunion.rb :

class Reunion < ApplicationRecord
  self.table_name = 'reuniones'

  belongs_to :planta
  belongs_to :centro_costo
  belongs_to :producto
end

meetings_controller.rb :

class ReunionesController < ApplicationController
  # más métodos

  def create
    reunion = Reunion.new(reunion_params)

    if reunion.save
      # acciones para guardado exitoso
    else
      # acciones en caso de error
    end
  end

  private
  def reunion_params
    params.require(:reunion)
          .permit(:planta_id, :centro_costo_id, :producto_id)
          .merge(emailsoli: current_user.email, nombresoli: current_user.name)
  end
end

Additionally (if the logic of your application allows it) you could evaluate modifying the Reunion model so that, instead of having the attributes emailsoli and nombresoli , you have a relation with User , avoiding registering two Sometimes the mail and name of the user.

Considering this change, the previous code would look like this:

reunion.rb :

class Reunion < ApplicationRecord
  self.table_name = 'reuniones'

  belongs_to :planta
  belongs_to :centro_costo
  belongs_to :producto
  belongs_to :user
end

user.rb :

class User < ApplicationRecord   
  has_many :reuniones

  # más relaciones, validaciones, métodos, etc,
end

meetings_controller.rb :

class ReunionController < ApplicationController
  # más métodos

  def create
    reunion = Reunion.new(reunion_params)

    if reunion.save
      # acciones para guardado exitoso
    else
      # acciones en caso de error
    end
  end

  private
  def reunion_params
    params.require(:reunion)
          .permit(:planta_id, :centro_costo_id, :producto_id)
          .merge(user_id: current_user.id)
  end
end
    
answered by 18.10.2017 в 16:11