I have class methods like these in a “message” model:
def delete_all_users_messages(user_id, parent_id)
message = Message.find_by_parent_id(parent_id)
message.children.where(:sender_id => user_id ).update_all(:sender_status => 1)
message.children.where(:recipient_id => user_id ).update_all(:recipient_status => 1 )
thread = message.message_thread
thread.update_attribute(:sender_status, 1) if thread.sender_id == user_id
thread.update_attribute(:recipient_status, 1) if thread.recipient_id == user_id
if thread.sender_status == 1 && thread.recipient_status == 1
thread.delete
Message.delete_all(:parent_id => parent_id)
end
end
def delete_all_users_selected_messages(message_ids, user_id, parent_id)
Message.where(:id => message_ids, :sender_id => user_id).update_all(:sender_status => 1)
Message.where(:id => message_ids, :recipient_id => user_id).update_all(:recipient_status => 1)
Message.where('id != ? AND parent_id = ?', parent_id, parent_id).where(:sender_status => 1, :recipient_status => 1).delete_all
thread = MessageThread.find_by_message_id(parent_id)
children_exist = thread.message.children.where('id != ? AND parent_id = ?', parent_id, parent_id).any?
unless children_exist
thread.delete
thread.message.delete
end
I use them in my messages_controller like this:
def destroy_all_messages
Message.delete_all_users_messages(current_user.id, params[:format])
flash[:success] = "Messages deleted"
redirect_to messages_path
end
def destroy_selected_messages
Message.delete_all_users_selected_messages(params[:message_ids], current_user.id, params[:format])
flash[:success] = "Messages deleted"
redirect_to :back
end
I would like to also return an error message if something went wrong.. but because all the logic for deleting messages is in my model it’s quite hard to do this.
Can anyone provide a solution with an example of how I could use some kind of condition to show my success message if messages were deleted and an error if they weren’t because something went wrong. There must me some kind of markers I can put in the class methods to confirm they have passed a certain point successfully.
Thanks for your time
Kind regards
There are two suggestions I’d make for you here.
The first is have your methods return false if what they were called to do didn’t happen. So, have something like this:
Then in your controller you can check the status of the method:
This is the method I would recommend; if you need multiple error messages for different steps in the process, I would break apart your delete_all_user_messages method into separate components, each one indicating true or false for whether they succeeded or failed.
Alternatively, you could raise custom error messages and rescuing them in your code. Something like this:
And then in your controller you rescue ThreadNotDeleted and deal with it there. While this works I think the other method is preferable.