简体   繁体   English

Ruby on Rails - 与模型的多对多关联

[英]Ruby on Rails - many to many association with model

Im trying to create a messaging system in Rails. 我正在尝试在Rails中创建一个消息传递系统。 The association of users to conversations should be of kind many to many, so that users can have multiple conversations and conversations multiple users. 用户与会话的关联应该是多对多的,因此用户可以与多个用户进行多次对话和对话。 Therfore i created the three tables users, conversation_relations and conversations and a model for each. 因此,我创建了三个表用户,conversation_relations和对话以及每个用户的模型。

the models look like: 这些模型如下所示:

class User < ActiveRecord::Base
    has_many :conversation_relations
    has_many :conversations, through: :conversation_relations
end

class Conversation < ActiveRecord::Base
    has_many :conversation_relations
    has_many :users, through: :conversation_relations
end

and

class ConversationRelation < ActiveRecord::Base
    belongs_to :user
    belongs_to :conversation
end

My problem is, when i try to assign multiple users to a conversation, the entry in the conversation_relations table is updated instead of creating a new entry. 我的问题是,当我尝试将多个用户分配给对话时,会更新conversation_relations表中的条目,而不是创建新条目。

eg (on console): 例如(在控制台上):

conversation = Conversation.create()
user1 = User.find(1)
user2 = User.find(2)
relation = ConversationRelation.new()

conversation.conversation_relations << relation
user1.conversation_relations << relation
user2.conversation_relations << relation

The problem occurs in the last line, because it updates the row created by user1.conversation_relations << relation instead of creating a new one. 问题出现在最后一行,因为它更新了user1.conversation_relations << relation创建的行,而不是创建一个新行。 Do i need to change something in the models or is the assignment awkward? 我是否需要更改模型中的某些内容或者作业是否尴尬?

Instead of conversation.conversation_relations << relation 而不是conversation.conversation_relations << relation

you must use conversation.conversation_relations.create(params) 您必须使用conversation.conversation_relations.create(params)

With the value returned by the given option you can use now << and the new conversation_relation will be added 使用给定选项返回的值,您可以立即使用<<并添加新的conversation_relation

Just do 做就是了

user1.conversations << conversation
# or
conversation.users << user1

no need to do ConversationRelation.new, rails will take care of this 不需要做ConversationRelation.new,rails会处理这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM