Rails acts as taggle on filter by multiple tags

2019-02-11 07:24发布

问题:

I have a model, Tasks, that can be tagged with the acts as taggable on gem.

The route: get 'mainpage/:tag', to: 'mainpage#index', as: :tag

Right now, when you click on a tag, it brings you to all tasks with that tag.

What I'd like to do is make it so that once you're on a tag page, clicking an additional tag further filters the results with the clicked tag name.

Ex.

On page for tag bills (mainpage/bills) displays:

Cable (tagged with: tv, credit card. bills)

Chairs (tagged with: credit card, bills)

table (tagged with: furniture, bills, salad)

When I click on the 'credit card' tag while on the bills tag page, I'd like to have it display only those tasks which are both a bills tag AND and credit card tag.

I'm flying a bit blind as how to do this.

Thanks for any help or suggestions

回答1:

From http://guides.rubyonrails.org/routing.html section 3.11:

get 'mainpage/*tags, to: 'mainpage#index', as: :tag

Adding this route allows you to have URLs like /mainpage/bills and /mainpage/bills/tv/furniture.

The first URL would come into your mainpage#index method with params[:tags] == 'bills', while the second one would come in with params[:tags] == 'bills/tv/furniture'. You could then simply split params[:tags] on /.

Note, for seo purposes, you probably want to come up with some nomenclature for the URLs, i.e. the tags are always alphabetical in the URL or something like that.