1

I am using the kaminari gem for pagination. I have a resources controller which paginates perfectly (due to the simple nature of the ordering). That can be seen here:

@resources = Resource.order("created_at desc").page(params[:page]).per(25)

That just sorts them by latest first. when i do .class it appears thats an activerecord::relation

On my tags though, I want to sort them by a relationship (the number of resources assigned to that tag)

@tags = Tag.all.sort{|a, b| b.number_of_resources <=> a.number_of_resources}.page(params[:page]).per(50)

It gives me the error however undefined methodpage' for #`

Tallboy
  • 12,847
  • 13
  • 82
  • 173

2 Answers2

0

Tag.all returns an Array, hence your #page call failing, as it expects an ARel relation.

If #number_of_resources maps to a DB column, then all you need to do is:

Tag.order('number_of_resources').page(params[:page]).per(50)

If it's not, you either need to add it to the Tag database table, or just do your sort/paginate in Ruby rather than using kaminari. This will be feasible if the number of tags is under ~1000 or so.

If you do add the info to the db, check out this post: Counter Cache for a column with conditions?

Community
  • 1
  • 1
Irongaze.com
  • 1,639
  • 16
  • 22
0

you should do something like: 1) joins the two tables, 2) group rows by tag, 3) count how many rows belongs to each group, 4) order using that new column with the count

you should make a good sql statement and then you can call pagination

arieljuod
  • 15,460
  • 2
  • 25
  • 36