I have a comments model that can have comments to comments (child comments), I want that in the model, when updating the state of the parent comment, the new state of the parent comment is updated to the states of the child comments, I can do it from the controller, but it is an additional UPDATE, I think there is a way to do it for the model and make it a one-time update.
In the controller I have:
class ComentariosController < ApplicationController
# ... fragmentos de codigo no relevante
def update
respond_to do |format|
if @comentario.update(comentario_params)
@comentario.comentario_hijos.update_all(estado: @comentario.estado)
else
format.html { render :edit }
end
end
end
# ... fragmentos de codigo no relevante
def comentario_params
params.require(:comentario).permit(:texto, :estado, :comentario_padre_id)
end
end
In the model I have:
class Comentario < ApplicationRecord
has_many :comentario_hijos, dependent: :destroy, foreign_key: :comentario_padre_id, class_name: :Comentario
belongs_to :comentario_padre, optional: true, class_name: :Comentario
validates :estado,
inclusion: { in: ['A', 'N']
}
end
Correct me if I'm wrong, but in
@comentario.update(comentario_params)
you are updating the state of the parent comment along with other attributes , while in@comentario.comentario_hijos.update_all(estado: @comentario.estado)
you are only updating the fieldestado
, right?There is no way (as far as I know and that is worth the effort to build that single query vs making 2
UPDATE
that after all is nothing for your DB engine) to make a single oneUPDATE
where you update multiple comment fields, including the fromestado
, but for certain comments (in your case, where thecomentario_padre_id
is equal toid
) just change the field fromestado
.On the other hand, what ifyou can do, if you just want to update the state field, for both parent and child, it is in your model to do something like:
and in your controller have an exclusive action to change the state of a comment and all its children:
And it bears repeating, this action would only focus on changing the field
estado
, not other fields, but it would do what you require which is to change all the states in oneUPDATE
.