每個字符has_many對話(通過:聊天室)和每個對話has_many字符(通過:聊天室)。一個角色可能只有一個對話只涉及一個其他角色(兩個參與者),以及涉及相同角色和其他角色(三個或更多參與者)的其他對話。Rails的activerecord通過關係選擇記錄的計數has_many
我想構建一個只選擇雙參與者對話的查詢。
以下給出一個丟失的FROM子句條目錯誤。我已經嘗試了很多排列組合,並且無法正確使用它。任何幫助將不勝感激。
字
has_many :chats, foreign_key: "character_id",
dependent: :destroy
has_many :conversations, through: :chats, source: :conversation
對話
has_many :chats, foreign_key: "conversation_id",
dependent: :destroy
has_many :characters, through: :chats, source: :character
def self.FindOneToOneConversation(sender, recipient)
@sender = Character.find_by(callsign: sender)
@recipient = Character.find_by(callsign: recipient)
@senderConversations = @sender.conversations
@senderAndRecipientConversation = @senderConversations.joins(:characters)
.where(characters: {id: @recipient.id})
.having("COUNT(character.id) < 3")
return @senderAndRecipientConversation.first # .first because @senderAndRecipientConversations is a collection
end
日誌:
PG :: UndefinedTable:錯誤:缺少FROM子句爲表 「性格」 進入第1行:..._ 「 」ID 「= $ 1」 字編號「= $具有2 COUNT(人物.... ^
:選擇 」「。* FROM 」對話的對話「 INNER JOIN 」聊天「, 」chats_conversations_join「 ON」 chats_conversations_join 「。」conversation_id「=」conversations「。」id「INNER JOIN」characters「ON」characters「。」id「=」chats_conversations_join「。」character_id「INNER JOIN」chats「ON」conversations「。」id「=」chats 「。」conversation_id「WHERE」chats「。」character_id「= $ 1 AND」characters「。」id「= $ 2 HAVING COUNT(character.id)< 3 ORDER BY」conversations「。」id「ASC LIMIT 1 Completed 500 Internal服務器錯誤在24ms(ActiveRecord:1.1ms)
ActiveRecord :: StatementInvalid(PG :: UndefinedTable:ERROR:miss表示「字符」的FROM子句條目 LINE 1:..._ id「= $ 1 AND」characters「。」id「= $ 2 HAVING COUNT(character ....
我希望這可以工作,但它給出了這樣的錯誤:
缺少FROM子句條目表「對話」
@senderAndRecipientConversation = Conversation.select('*, COUNT(chats.character_id)')
.from("(#{@senderConversations.to_sql}) AS sender_conversations")
.joins("
INNER JOIN chats
ON sender_conversations.id = chats.conversation_id
GROUP BY chats.conversation_id
HAVING COUNT(chats.character_id) < 3
")
針對第一個答案,以下是有缺陷的,我不明白爲什麼 - 它發現涉及的所有對話收件人,不只是一對一的對話:
@senderAndRecipientConversation = @senderConversations.joins(:characters)
.where(characters: {id: @recipient.id})
.group('conversations.id')
.having("COUNT(characters.id) < 3")
您能向我們展示錯誤的完整堆棧跟蹤嗎? – niceman