Nomethoderror: Undefined method `similaridade_com' for #<Class:0x007ff55873cad0> - Ror

Asked

Viewed 220 times

1

I’m trying to create an attribute of the class that will be an array of similarities between users. Is there something wrong with this construction? There’s a better way to do it?

class Usuario < ActiveRecord::Base

require 'matrix'

@@similaridade = Matrix.build( self.all.size, self.all.size) 
                          {|x,y| similaridade_com self.find(x + 1), self.find(y + 1) }

def self.similaridade
  @@similaridade
end

private

  def similaridade_com(usuario1, usuario2)
    ...
  end

end

When I’m calling Usuario.similaridade in the rails console is making the mistake Nomethoderror: Undefined method `similaridade_com' for #Class:0x007ff55873cad0

  • Ever tried to put self. in front of the method call?

  • You are using a class variable (@@similarity) that when initialized uses an instance method (similarity_com). Have you tried Andrey’s tip?

2 answers

2

If there are no restrictions, it would be better to create a table with the has_many through relation:

class Usuario < ActiveRecord::Base
  has_many :similaridades
  has_many :usuarios, through: :similaridades
end

class Similaridade < ActiveRecord::Base
  belongs_to :usuario
  belongs_to :similar, :class_name => 'Usuario'
end

So you can define a 'user' method as:

def similaridade_com(usuario)
  self.similaridades.find_by(similar: usuario)
end

I considered that you use pluralization in Portuguese, but always try to encode in English to take advantage of Rails conventions.

  • The idea is to leave in memory to make as little access as possible to the bank, since these operations are very time consuming, I was seeing in using Redis, but consider whether this solution is feasible since I have little knowledge...

0

You stated this method in the section private. That means that the method is private. Private methods can only be called by the recipient himself, the self.

If for test merit, use the Object#send. What he does is to call a method from an object instance, regardless of the visibility of that method (private, protected, public).

usuario = Usuario.new
usuario.send(:similaridade_com, param1, param2)
# => ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.