conversations_controller.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. end
  11. def new
  12. @conversation = Conversation.new
  13. @conversation.messages.build
  14. end
  15. def create
  16. @conversation = Conversation.new(conversation_params)
  17. @conversation.messages.each{ |message| message.user = current_user }
  18. if @conversation.save
  19. for id in params[:conversation][:user_ids].uniq
  20. @conversation.users << User.find(id)
  21. end
  22. unless @conversation.users.include? current_user
  23. @conversation.users << current_user
  24. end
  25. if @conversation.save
  26. flash[:success] = "Created conversation"
  27. redirect_to @conversation
  28. else
  29. render :new
  30. end
  31. else
  32. render :new
  33. end
  34. end
  35. private
  36. def set_conversation
  37. @conversation = Conversation.find(params[:id])
  38. end
  39. def check_permission
  40. unless current_user.conversations.include? @conversation
  41. flash[:danger] = "You are not part of this conversation"
  42. redirect_to root_path
  43. end
  44. end
  45. def conversation_params
  46. params.require(:conversation).permit(:name, messages_attributes: [:content])
  47. end
  48. end