Direct link to send a message to a user Rails

646 views Asked by At

I'm new on Ror, I would like to add in my app, on my product show:

  • a link which permits clients to send a new message to the product-seller.

The new message created should include:

  • the product.id in the topic
  • a text area
  • the recipient seller name (hiding all the other users)
  • submit button to send the message. I use devise for my users and the gem mailboxer for the messaging feature.

I don't succeed to create the right link and also to hide all the users in order to send the message only to the product seller.

reservations/_form.html.erb:

<% if user_signed_in? && current_user != @user %>
<%= link_to "Contact seller", conversations_path(sender_id: current_user.id, recipient_id: @user.id), method: 'post', class: 'btn btn-md btn-danger' %>
<% end %>

messages.new.html.erb

<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2 text-center">

    <h3>Send a message</h3>

      <%= form_tag messages_path, method: :post do %>
      <div class="form-group">
        <%= label_tag 'message[subject]', 'Subject' %>
        <%= text_field_tag 'message[subject]', nil, class: 'form-control', required: true %>
      </div>

      <div class="form-group">
        <%= label_tag 'message[body]', 'Message' %>
        <%= text_area_tag 'message[body]', nil, cols: 3, class: 'form-control', required: true %>
      </div>

      <div class="form-group">
        <%= label_tag 'recipients', 'Choose a recipient' %>
        <%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it' %>
      </div>

      <%= submit_tag 'Send message', class: 'btn btn-md btn-danger' %>
      <% end %>
      <br>
      <br>
    </div>
  </div>
</div>

messages_controller.rb:

class MessagesController < ApplicationController
  before_action :authenticate_user!

def new
  @chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]
end

  def create
    recipients = User.where(id: params['recipients'])
    conversation = current_user.send_message(recipients, params[:message][:body], params[:message][:subject]).conversation
    flash[:success] = "Message has been sent!"
    redirect_to conversation_path(conversation)
  end
end

routes.rb:

  resources :conversations, only: [:index, :show, :destroy] do
    member do
      post :reply
      post :restore
      post :mark_as_read
    end
    collection do
      delete :empty_trash
    end
  end

  resources :messages, only: [:new, :create]
0

There are 0 answers