Paladini
Paladini

Reputation: 4572

How to make "filters" in a view?

I'm developing a Rails application and I have a huge doubt: how to make "filters" in a View?

In my project I have a model called Site (stores links of websites), this websites have association with Country, in the way that one Country has_many Site. Currently, I can (easily) show all sites and their related countries, but now I want filter by country, not just show the sites and the Country that they belongs to. I mean, I want select one Country and show just websites from this Country.

I already have the database, everything is correct in Model and I know how I can do that with ActiveRecord, but I don't know how I can do this in View.

I though in send Country by GET and return to the same page. So, the controller of the same model can check if the requested page have some params. If yes, show the page with the requested Country. But I don't know if this is the best way, if this is the right way - and how I can properly do that.

How I can do that?

If you need some code, I can paste here, but I think this isn't necessary.

Upvotes: 0

Views: 128

Answers (2)

Tyler
Tyler

Reputation: 11499

Depending on how many sites and countries you have, I might just load them all at once and then use js to show/hide the ones you want. For example, you could do:

<% @sites.each do |site| %>
  <a href="<%= site.url %>" class="country-link <%= site.countries.map(&:name).join(" ") %>"><%= site.name %></a>
<% end %>

Then you can use e.g. jQuery to hide them all and then only show which ones are in the dropdown/link:

$('.country-link').hide()
$('<trigger>').on 'click', () ->
  $('.country-link').hide()
  $('<country name>').show()

Upvotes: 1

CDub
CDub

Reputation: 13354

There are a couple ways (off the top of my head) that you could do this...

  1. You could do a drop-down menu that adds a query parameter to the end of the URI. You'd then parse that (either with a page refresh or asynchronously) and filter the results based on what that query parameter is. Example: www.example.com/sites?country=us could show only sites from the United States).

  2. You could do this with routes, where you'd have a route that matches a URI like GET /sites/:country_code - this would work in a similar way, where you would have a parameter in your controller called country_code and could then filter based on that parameter. This is much cleaner implementation, in my opinion.

Again, personally, I prefer option 2 above, but either should get you what you want.

Upvotes: 1

Related Questions