ruby-on-railsmessagingmailboxer

rails showing ActiveRecord_Associations error while adding a send message link


I have a rails app where users can add a post and other users can comment on them i was trying to add a direct message link with the users who comment, i tried something like this following a suggestion on stackoverflow

_form.html.erb

<%= form_for :conversation, url: :conversations, html: { class: "" } do |f| %>
<div class="form-group">
  <%= f.label :recipients %>
  <%= hidden_field_tag(:recipient_id, "#{@user.id}") %></div>
<div class="form-group">
  <%= f.label :subject %>
  <%= f.text_field :subject, placeholder: "Subject", class: "form-control" %>
</div>
<div class="form-group">
  <%= f.label :message %>
  <%= f.text_area :body, class: 'form-control',placeholder: "Type your message here", rows: 4  %>
</div>

<%= f.submit "Send Message", class: "btn btn-success" %>

<% end %>

show.html.erb

<%= link_to 'Send Message', new_conversation_path(:recipient_id => @post.comments.user.id), class: 'send-message-icon' %>

**conversation_controller.rb**
def new
    @user = User.find_by(id: params[:recipient_id])
  end

   def create
    recipients = User.find_by(id: params[:recipient_id])
    conversation = current_user.send_message(recipients, conversation_params[:body], conversation_params[:subject]).conversation
    flash[:success] = "Your message was successfully sent!"
    respond_to do |format|
      format.html {redirect_to conversation_path(conversation)}
      format.js
    end
  end

But am getting the following error

undefined method `user' for #<Comment::ActiveRecord_Associations_CollectionProxy:0x93b1018>

I am using mailboxer gem for messaging functionality.


Solution

  • Assuming you have a comments table that has a column user_id

    <% @post.comments.each do |comment| %>
      <%= link_to 'Send Message', new_conversation_path(recipient_id: comment.user_id) %>