Search code examples
ruby-on-railsnamed-scope

Named Scope in Rails to order Record by number of associated Records


Im new to Rails. I have 2 nested resources: Photos and tags.

Photos
  Tags
end

Photos has many tags, and tag belongs to photo.

I want to create a scope that orders Photos by number of tags in them. The relation they have is in Tags:

t.integer "photo_id"with that column.

How should I make my scope If I want first the photos with most tags?

Thanks a lot.


Solution

  • I suggest reading some documentation about belongs_to and has_one associations.

    In particular interest to you may be the :counter_cache option for belongs_to in order to keep track of how many tags each photo has. This will also give you a column to sort (and index) by as well.

    From there, it should be pretty trivial to create the scope you need from examples all over the internet.