0

I'm trying to make a feed page where users can see the popular posts and the posts of whom they followed. This what I tried (but failed):

  @popularPosts = Post.where(cached_votes_score > '2')

returning an error.

undefined local variable or method `cached_votes_score' for #<PagesController:0x007fa2ae08f630> Did you mean? cache_store

Any thought on this?

Malek Zalfana
  • 318
  • 2
  • 11

1 Answers1

1

What you want is done:

Post.where('cached_votes_score > 2')

What you where trying to do was interpreted as trying to call a method cached_votes_score in the controller and comparing if its returned value is greater than '2'.

Rails doesn't have a Railsism to do greater than comparisons, so you do a SQL segment to accomplish it.

Leonel Galán
  • 6,993
  • 2
  • 41
  • 60
  • 1
    I think too just Post.where('cached_votes_score > 2') – Hopscott Jul 29 '16 at 16:25
  • You are absolutely right, specially if the 2 isn't changing as it appears to be in this example. I will update my response to help future readers. – Leonel Galán Jul 29 '16 at 19:02
  • And from 0 ->9, it's `where(' -1 < cached_votes_score < 10')` ? – Malek Zalfana Jul 30 '16 at 13:10
  • Nope, that's not valid SQL. Remember know you are simply doing SQL segments inside Rails' `.where`. You want to do `'cached_votes_score >= 0 AND cached_votes_score < 10'`. Rails Active Record is a great way to get you started running queries, but its important for every Rails developer to learn the underlaying SQL as well. – Leonel Galán Aug 01 '16 at 19:00