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