Home Inconsistent rails method `exists` and `any?`
Reply: 0

Inconsistent rails method `exists` and `any?`

user8034 Published in September 20, 2018, 12:43 pm

I'm working on a Ruby on Rails based chat. So I initially create a conversation between 2 clients when they add each other as friends and my model for Conversation is as follows:

class Conversation < ActiveRecord::Base
  has_many :messages
  belongs_to :player_client
  belongs_to :client

Now when the player_client clicks a specific button I want to create an automated message for them. This should only happen if they've never sent a message to each other i.e. the conversation has no associated messages.

Trying the following methods from the console:

@conversation = Conversation.find(7)
> False
> True
> False

Which are all expected values. But adding any of these methods in my Rails code throws an error:

NoMethodError (undefined method `messages' for #<Conversation::ActiveRecord_AssociationRelation:0x007fa187ca1ec8>)`

Which I guess is showing up because messages don't exist for that conversation so it can't find any association for that conversation. I'm not sure why this method would be inconsistent though.

EDIT: Adding the error causing code.

conversation_with_player_client = @client.conversations.select{|c| c.player_client_id == @game.player_client.id}

if conversation_with_player_client.count == 0
  @conversation = @client.conversations.build({player_client_id: @game.player_client.id})
  @conversation = @client.conversations.where({ player_client_id: @game.player_client.id })

puts "the conversation we found was #{@conversation.inspect}"
# This gives the response
# #<Conversation id: 7, player_client_id: 1, client_id: 11, created_at: "2018-02-12 20:55:55", updated_at: "2018-02-12 20:55:55">
# in the console so it can get the conversation 

if @conversation.messages.any?

# this line is causing the error
share|improve this question
  • You should post the code that causes the error, but it seems you are applying the .messages to many conversations (or other association) and not a unique conversation. – Pablo Feb 12 at 22:02
  • @Pablo I added the code block as you suggested – anonn023432 Feb 12 at 22:08

4 Answers 4

active oldest votes
up vote 2 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.326486 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO