Search code examples
ruby-on-railsrubyactiverecordransackquerying

Rails - Using ransack to query a database through links


I recently discovered the ruby gem, ransack

Ransack can be used to query ActiveRecord databases by forms.

What I would like to do though, is query ActiveRecord by clicking on links.

Let's say I'm writing a sports blog and categorize articles.

Let's say my categories are football, basketball, baseball and hockey.

I could find articles related to basketball by writing this code

<%= search_form_for @q do |f| %>

  <%= f.label :category_eq, "Category" %>
  <%= f.search_field :category_eq %></br></br>

  <%= f.submit "Search", :class => 'submit-btn' %>

<% end %>

typing in basketball and pressing submit.

I would then see a list of articles relating to basketball.

What I would like to do is see the same thing, only by clicking on a link, ActiveRecord is queried.

I know you can do this by creating a bunch of different paths, a bunch of different controller actions, and in them querying ActiveRecord as follows

<% Article.where(category: 'basketball').each do |article| %>

  <%= article.title %>
  <%= article.author %>
  <%= article.content %>
  <%= article.category %>

<% end %>

That seems like a lot of extra work and there has to be a simpler way


Solution

  • You don't need to create any new routes. Just create a link with the appropriate q parameter(s):

    <%= link_to 'Basketball articles', q: {category_eq: 'Basketball'} %>
    

    The above link will go to the current URL, but with the Basketball query param. You can also pass the q param to a path or url helper:

    <%= link_to 'Basketball articles', articles_path(q: {category_eq: 'Basketball'}) %>