Keith Johnson
Keith Johnson

Reputation: 730

Passing a model method's output to its controller

I've defined this method in my Track model

def random_number
    max = Article.maximum(:id)
    id = rand(1..max)
    return id
end

and am trying to pass it to the Tracks controller to render another classes object in the tracks controller's index view like so:

def index
  @tracks = Track.all
  id = Track.random_number
  @random = Article.find_by_id(id)
end

Yet keep getting a NoMethodError "undefined method `random_number' for #".

Any tips on how to render this correctly?

Thanks!!

Upvotes: 0

Views: 73

Answers (1)

MurifoX
MurifoX

Reputation: 15089

You are calling it like it were a class method. Add self to the method an you are good to go.

def self.random_number

The way it is now, you can only access the method using an instance of the Track class.

@track = Track.new
@track.random_number

Upvotes: 3

Related Questions