使用acts-as-taggable-on gem对关联进行排序

时间:2020-12-22 11:06:58

I am trying to dynamically sort a table of Posts by :type using acts-as-taggable-on gem.

我正在尝试通过:使用acts-as-taggable-on gem输入来动态地对文章表进行排序。

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

假设我的Post对象有3列:user、title和date。通过输入我的controller @entries = Post,我可以轻松地对Post表进行排序。order(sort_column + " " + sort_direction).page(params[:page])

sort_column and sort_direction being referred as:

sort_column和sort_direction分别表示为:

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:

但是,Post也可以有一个类型附加到它。在我的Post模型中,我有:

acts_as_taggable
acts_as_taggable_on :types 

and in the table of my view I simply display the tag by writing:

在我的视图中,我只是通过写来显示标签:

views/posts/_posts.html.slim

视图/文章/ _posts.html.slim

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

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

是否有一种简单的方法按字母顺序对表进行排序?

1 个解决方案

#1


2  

The acts-as-taggable-on gem adds polymorphic association. You can take full advantage of Active record.

acts-as- taggabon gem添加了多态关联。你可以充分利用主动记录。

You have to do something like this. This will give your post in alphabetical order.

你必须做这样的事情。这将按字母顺序给你的职位。

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

Hope this help.

希望这个有帮助。

#1


2  

The acts-as-taggable-on gem adds polymorphic association. You can take full advantage of Active record.

acts-as- taggabon gem添加了多态关联。你可以充分利用主动记录。

You have to do something like this. This will give your post in alphabetical order.

你必须做这样的事情。这将按字母顺序给你的职位。

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

Hope this help.

希望这个有帮助。