John
John

Reputation: 443

NoMethodError - undefined method error - ActiveRecord

I'd like to return a random webpage that I can display as a link in a view but I can't get the method to work properly:

Error:

NoMethodError: undefined method `randomize_webpages' for #<ActiveRecord::Relation::ActiveRecord_Relation_Webpage:0x00000101d84e68>

Webpage Model

 def randomize_webpages
    shuffle.first
 end

WebpagesController

def index
  @webpages = Webpage.all
end

CSV seeder for Webpage

link
http://www.buzzfeed.com
http://www.reddit.com
http://boston.com
http://phys.org
http://www.popsci.com
http://www.technologyreview.com
http://techcrunch.com

View Index.html.erb

<%= link_to 'Take Me Anywhere But Here', @random_page %>

Upvotes: 0

Views: 885

Answers (4)

delphaber
delphaber

Reputation: 319

You could add a class method to your model

class WebPage < ActiveRecord::Base     
  def self.random
    order('RAND()').first
  end
  ....
end

Then you can call it from as WebPage.random in your controller, save to an instance variable, and use that instance variable in your view.

Please: note that 'RAND()' is MySQL specific. If you do not use MySql, search for the correct syntax (if any)

Upvotes: 0

CDub
CDub

Reputation: 13354

It needs to be a class method, then you could use sample:

def self.randomize_webpages
  all.sample
end

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176552

You need to define the method as a class method of the model

class Webpage
  def self.randomize_webpages
    shuffle.first
  end
end

instead of

class Webpage
  def randomize_webpages
    shuffle.first
  end
end

Please note that the method is very inefficient. You are loading all the records and then selecting one. There are more efficient ways.

One possible improvement is to select only the ID, then query for that ID. Another alternative is to delegate to the underlying driver, assuming it supports the query.

Upvotes: 2

zrl3dx
zrl3dx

Reputation: 7869

Aren't you calling randomize_webpages on @webpages, are you? This is a collection, so you have to do something like @webpages.first.randomize_webpages or iterate over them (you didn't include relevant code so I can't tell what you want to do) to get this working.

Upvotes: 0

Related Questions