3

so I have a very simple model called Movies. I'm trying to add a class method which returns a tidy list of the ratings assigned to movies in the database. It seems I'd want to call Movie.uniq.pluck(:rating)

So I've added the method like so:

class Movie < ActiveRecord::Base

    def self.all_ratings
        self.uniq.pluck(:rating)
    end

end

but it just doesn't work. When it runs I get: undefined methoduniq' for #`... I've tried including ActiveRecord::Calculations but that doesn't seem to help either. I also put a breakpoint in after 'def...' to inspect what methods self had and sure enough, uniq wasn't among them...

I'm clearly doing something wrong, but I just don't quite get what it is.

Anyone have any ideas?

ó_ò
BigglesB
  • 123
  • 2
  • 8

2 Answers2

2

uniq is a Ruby method, and available even for 1.8.7. The problem is uniq is an Array method.

So you probably need to call uniq on something like Movie.all.

Benjamin Tan Wei Hao
  • 9,621
  • 3
  • 30
  • 56
  • Yes, but in the more recent Rails documentation, ActiveRecord::Calculations.uniq.pluck(:column_name) is well defined. I hadn't accounted for the fact that it was more recent than the version I was using, hence the 2 day headache. Of course, there are more verbose ways to do the same thing, as you suggest. – BigglesB Aug 10 '12 at 07:07
  • 1
    I was actually able to use uniq on a class for Rails 5.0.1 but it no longer worked in 5.1.2 and had to add the .all method to my class. Thanks! – fatfrog Jul 12 '17 at 04:21
0

uniq is an array method. When you put self.uniq inside self.all_ratings, self refers to the Movie class, it wont point to any collection

So first get the collection as you want

result = Movie.all

(or)

result = Movie.where({})

and then use the uniq method for the result

pdpMathi
  • 777
  • 3
  • 7