1

I'm using the cassandra gem. http://docs.datastax.com/en/developer/ruby-driver/3.0/features/

In my model I'm doing the following:

class User < ApplicationRecord
  require 'cassandra'

  def initialize
    @cluster = Cassandra.cluster
  end

  def session
    @cluster.connect('capsula')
  end

  def total_users
    result = session.execute("SELECT * FROM users")
    result.size
  end

end

But when I call the total_users method the error is shown:

undefined method `connect' for nil:NilClass

def session
  @cluster.connect('capsula')
end

I wanted to save the connection on a variable so it would not be necessary to make a new connection for each request.

Hizqeel
  • 947
  • 3
  • 20
  • 23
Emília Parsons
  • 135
  • 1
  • 6

1 Answers1

2

It looks like @cluster is nil, so it hasn't been properly initialized.

It isn't a good idea to define initialize for Rails models. You could use callbacks instead.

If I understand it correctly, the session doesn't depend on the User, and could be defined for User class instead of User instances :

class User < ApplicationRecord
  require 'cassandra'

  class << self
    def cassandra_session
      @session ||= Cassandra.cluster.connect('capsula')
    end
  end

  def total_users
    result = User.cassandra_session.execute("SELECT * FROM users")
    result.size
  end
end

Using @session ||= means that @session will be initialized once and kept in cache afterwards :

@x ||= 1
@x ||= 2
@x ||= not_even_called
puts @x
#=> 1
Community
  • 1
  • 1
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124