Trying to create a chatroom app, and I'm not sure where to use my associations correctly when creating a chatroom conversation
SCHEMA
create_table "chat_messages", force: :cascade do |t|
t.string "body"
t.integer "user_id"
t.integer "conversation_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "conversations", force: :cascade do |t|
t.string "room_name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "users", force: :cascade do |t|
t.string "user_name"
t.string "email"
t.string "password"
t.string "password_digest"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
class User < ApplicationRecord
has_secure_password
has_many :chat_messages
has_many :conversations, through: :chat_messages
end
class Conversation < ApplicationRecord
has_many :chat_messages
has_many :users, through: :chat_messages
end
class ChatMessage < ApplicationRecord
belongs_to :user
belongs_to :conversation
validates :body, presence: true
end
I can create a user, and I would like to be able to set the name of a chatroom conversation by using
user = User.first
user.conversations.create(room_name: 'my chatroom')
This prevents me from creating the conversation because the ChatMessage is the through association model, and it needs a body property, but I don't need to create a message when creating the name of the room. I have a hard time understanding how and when to use associations.
I tried adding a user_id to the conversations table, but I'm still confused as to how it works with the other models.
First take a look at the association you have created.
here conversation between
conversationanduseris throughchat_messagesconversation=>chat_messages=>userSo Creating a
conversationwithuserwithoutchat_messageswill break your code.You can add
user_id/admin_idin theconversationtable and make changes in associations as below:And while fetching you can fetch the
userasconvesation.adminPlease have a look at the docs here. I hope this will help you.