How to create a model without the associated model through a has many relationship

30 Views Asked by At

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.

1

There are 1 best solutions below

0
Amol Mohite On

First take a look at the association you have created.

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

here conversation between conversation and user is through chat_messages

conversation => chat_messages => user

So Creating a conversation with user without chat_messages will break your code.

You can add user_id/admin_id in the conversation table and make changes in associations as below:

class Conversation < ApplicationRecord
  has_many :chat_messages
  has_many :users, through: :chat_messages
  has_one  :admin, class_name: 'User',foreign_key: 'user_id'
end

And while fetching you can fetch the user as convesation.admin

Please have a look at the docs here. I hope this will help you.