0

So I am trying to implement a messaging system in my application, and I have no intention on using any of the gems. I've seen most of them and I'm able to use them. But for learning sake, I want to learn how it works and build one from scratch and be able to customize it how I want it.

I have looked around for tutorial but there isn't any tutorial or anything concrete information except for; this -> http://.novawave.net/public/rails_messaging_tutorial.html, but unfortunately link is down or this -> Rails threaded private messaging, but I still cant wrap my head around everything.

So hope this thread will serve as a point of reference for others.

So based off this thread Rails threaded private messaging, this is what I have including the columns definitions. But I'm having problem wrapping my head around the logic on adding multiple users in a conversation. The way that I see this:

  1. Click on send a message, which will trigger a new conversation object
  2. Add a subject, and select users that I want in the conversation <-- this is where it gets cloudy
  3. at the bottom without of that same form without any ajax, I guess I could render message form which will submit the text?

Ok so how do I put multiple user ids in the conversation table users_id column? There is a suggestion to use 'act_as_taggable' gem from this thread -> Rails threaded private messaging comes in? If so, how is the database is going to know that it should select all these user in a certain conversation object.

class Conversation < ActiveRecord::Base
 #columns -> :subject, :users_id

  has_many :messages
  has_many :participants
  has_many :users, :through => :participants
end



class Message < ActiveRecord::Base
 #columns -> :conversation_id, :sender_id, :read

  belongs_to :conversation
end

class Participant < ActiveRecord::Base
 #columns -> :user_id, :conversation_id

  belongs_to :conversation
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :conversations
  has_many :participants
end
Community
  • 1
  • 1
Woody008
  • 96
  • 1
  • 2
  • 9

1 Answers1

0

The conversations table should not have a user_id/users_id column as you have setup a many to many relationship in this case.

You can add users to a conversation by doing something like:

@conversation.users << @user
@conversation.save

Or in a form it would be something like:

<%= form_for Conversation.new do |f| %>
  <%= f.collection_select :user_ids, User.all, :id, :name, {prompt: true}, {multiple: true} %>
  <%= f.submit %>
<% end %>

You can get users in a conversation with @conversion.users.

Also, your user model should be:

class User < ActiveRecord::Base
  has_many :participants
  has_many :conversations, through: :participants
end
Chris Edwards
  • 3,514
  • 2
  • 33
  • 40