NoMethodError: undefined method 'similarity_com' for #Class: 0x007ff55873cad0 - RoR

1

I'm trying to create an attribute of the class that will be an array of similarity among users. Is there something wrong with this construction? Is there 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 am calling Usuario.similaridade on rails console it is giving the error NoMethodError: undefined method 'similarity_com' for #Class: 0x007ff55873cad0     

asked by anonymous 13.08.2014 / 22:39

2 answers

2

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

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 method in 'user' as:

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

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

    
20.08.2014 / 18:33
0

You declared this method in the private section. This means that the method is private . Private methods can only be called by the receiver itself, self .

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

usuario = Usuario.new
usuario.send(:similaridade_com, param1, param2)
# => ...
    
02.12.2018 / 19:04