尝试创建聊天室应用程序,而在创建聊天室会话时,我不确定在哪里正确使用我的关联
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
endclass 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,但我仍然不清楚它与其他模型的工作方式。
发布于 2022-11-04 07:19:29
首先,看看您创建的协会。
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这里conversation和user之间的对话是通过chat_messages进行的。
conversation => chat_messages => user
因此,使用没有conversation的user创建chat_messages将破坏您的代码。
您可以在user_id/admin_id表中添加conversation并在关联中进行更改,如下所示:
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
请看一下医生来了。我希望这能帮到你。
https://stackoverflow.com/questions/74311749
复制相似问题