首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过有多个关系创建没有关联模型的模型

如何通过有多个关系创建没有关联模型的模型
EN

Stack Overflow用户
提问于 2022-11-04 03:07:20
回答 1查看 15关注 0票数 0

尝试创建聊天室应用程序,而在创建聊天室会话时,我不确定在哪里正确使用我的关联

代码语言:javascript
复制
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
代码语言:javascript
复制
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

我可以创建一个用户,并且我希望能够通过以下方法设置聊天室会话的名称

user = User.first

user.conversations.create(room_name: 'my chatroom')

这使我无法创建会话,因为ChatMessage是直通式关联模型,它需要一个body属性,但在创建房间名称时不需要创建消息。我很难理解如何以及何时使用关联。

我尝试向conversations表中添加一个user_id,但我仍然不清楚它与其他模型的工作方式。

EN

回答 1

Stack Overflow用户

发布于 2022-11-04 07:19:29

首先,看看您创建的协会。

代码语言:javascript
复制
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

这里conversationuser之间的对话是通过chat_messages进行的。

conversation => chat_messages => user

因此,使用没有conversationuser创建chat_messages将破坏您的代码。

您可以在user_id/admin_id表中添加conversation并在关联中进行更改,如下所示:

代码语言:javascript
复制
class Conversation < ApplicationRecord
  has_many :chat_messages
  has_many :users, through: :chat_messages
  has_one  :admin, class_name: 'User',foreign_key: 'user_id'
end

在获取时,您可以将user提取为convesation.admin

请看一下医生来了。我希望这能帮到你。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74311749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档