Sorting by association using the "as action" attribute

I'm trying to dynamically sort the table Posts

by means of :type

using Acts-as with the on-taggable- gem.

Let's say my Post object has 3 columns: user, title and date. I can easily sort the Post table by inserting my controller@entries = Post.order(sort_column + " " + sort_direction).page(params[:page])

sort_column

and sort_direction

are referred to as:

def sort_column
  Post.column_names.include?(params[:sort]) ? params[:sort] : "published_at"
end

def sort_direction
  %w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
end

      

However, Post can also have a type attached to it . In my Post model, I have:

acts_as_taggable
acts_as_taggable_on :types 

      

and in my view table I just show the tag, write:

views / posts / _posts.html.slim

...
td.tags = entry.type_list.first.titleize unless entry.type_list.blank?
...

      

Is there an easy way to alphabetically sort a table by type ?

+3


source to share


1 answer


The gem acts-as-taggable-on

adds a polymorphic association. You can take full advantage of Active Recording.

You should do something like this. This will give you post

in alphabetical

order.



Post.includes(:taggings).joins(:types).order("tags.name")

      

Hope for this help.

+2


source







All Articles