Matthew Hui
Matthew Hui

Reputation: 3361

Rails: Filter content using link_to (links) instead of checkbox

I want to filter my content based on tags. I would rather use links instead of a checkbox form that filters content based on which tags are checked by the user. I currently generate links using the code below:

link_to tag.name, user_path(tags: tag.id)

This creates urls of the format ?tag=15

This works to display all content with tag=15 but the user should be able to select multiple tags.

When a user clicks on a second filter link the new tag should be appended to the tag param and now content with both tags should be displayed. Basically, I would like to generate urls that look like:

?tag[]=15&tag[]=1

Is it even possible to specify the tags param as an array in link_to? If so, how can I append subsequent tags to the end of the url? Is there a better way to accomplish filtering through links?

Upvotes: 0

Views: 804

Answers (1)

Hampei
Hampei

Reputation: 3896

I would create the links like this:

link_to tag.name, user_path(tags: "#{params[:tags]},#{tag.id})

And then in the controller use

@tags = params[:tags].split(',')

Upvotes: 1

Related Questions