Rails activerecord通过has_many:through查询计数记录

时间:2015-11-20 01:40:58

标签: ruby-on-rails activerecord

字符has_many :conversations, through: :chats,以及每个对话has_many :characters, through: :chats

character.rb

has_many :chats, foreign_key: "character_id", dependent: :destroy
has_many :conversations, through: :chats, source: :conversation
has_many :messages

conversation.rb

has_many :chats, foreign_key: "conversation_id", dependent: :destroy
has_many :characters, through: :chats, source: :character
has_many :messages

chat.rb

belongs_to :character
belongs_to :conversation

messages_controller.rb

def create
  @sender    = Character.find_by(callsign: params[:callsign])
  @recipient = Character.find_by(callsign: params[:recipient])
  # 1
  @senderConversations = @sender.conversations
  # 2
  @senderAndRecipientConversations = @senderConversations.joins(:characters).where(characters: {id: @recipient.id}) # works fine up to here
  # 3
  @conversationAssociation = @senderAndRecipientConversations.joins(:characters).group('conversations.id').having('count(characters.id) = ?', 2) # problem line!
  @conversation = @conversationAssociation.first
  if(@conversation.nil?)
    @conversation = @sender.conversations.create
    @recipient.conversations << @conversation
  end
  @message = @sender.messages.build(message_params.merge(:conversation => @conversation))
  if @message.save
    @conversation.messages << @message
    respond_to do |format|
      format.html do
      end
      format.js do
      end
    end
  else
    redirect_to request.referrer || root_url
  end
end

所有会话必须至少包含两个字符,而某些会话可能包含两个以上的字符(群聊​​)。

我试图构建一个三步查询,首先查找所有@发送者的对话,然后从这些对话中选择也涉及@recipient的对话,最后选择仅涉及的对话@sender和@recipient,没有其​​他角色。

前两个步骤正常。我无法获得第三步的代码。我管理的最好的是:

@senderAndRecipientConversations.joins(:characters).group('conversations.id').having('count(characters.id) = ?', 2)

此代码有什么问题?

0 个答案:

没有答案