conversations_controller.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. class ConversationsController < ApplicationController
  2. before_action :set_conversation, only: [:show]
  3. before_action :check_permission, only: [:show]
  4. def index
  5. @conversations = current_user.conversations.sort_by{
  6. |c| c.messages.last.created_at
  7. }
  8. end
  9. def show
  10. ConversationParticipation
  11. .where(user: current_user, conversation: @conversation)
  12. .update_all(viewed_at: Time.now)
  13. end
  14. def new
  15. @conversation = Conversation.new
  16. @conversation.messages.build
  17. end
  18. def create
  19. @conversation = Conversation.new(conversation_params)
  20. @conversation.messages.each{ |message| message.user = current_user }
  21. if @conversation.save
  22. for id in params[:conversation][:user_ids].uniq
  23. @conversation.users << User.find(id)
  24. end
  25. unless @conversation.users.include? current_user
  26. @conversation.users << current_user
  27. end
  28. if @conversation.save
  29. flash[:success] = "Created conversation"
  30. redirect_to @conversation
  31. else
  32. render :new
  33. end
  34. else
  35. render :new
  36. end
  37. end
  38. private
  39. def set_conversation
  40. @conversation = Conversation.find(params[:id])
  41. end
  42. def check_permission
  43. unless current_user.conversations.include? @conversation
  44. flash[:danger] = "You are not part of this conversation"
  45. redirect_to root_path
  46. end
  47. end
  48. def conversation_params
  49. params.require(:conversation).permit(:name, messages_attributes: [:content])
  50. end
  51. end