Search code examples
ruby-on-railsoophas-many

How to filter elements to be displayed from a has_many association in rails


Say I have 3 nested models through has_many association:

class Map
  has_many :countries
end

class Country
  has_many :cities
  belongs_to :map
end

class City
  belongs_to :country
  belongs_to :user
end

I have a view that show the maps -> countries -> cities through the MapsController, that's fine.

Now city has a :published attribute and I would like to filter that view to only cities that are published + unpublished and user == current_user.

I tried to assign the has_many association with the filtered objects, but the problem with this approach is that autosave will delete the objects that don't match the criteria.

I could filter the cities in the view, with a city scope and this pseudo code in the view:

@map.countries.each do |country|
  country.cities_published_and_unpublished_by_user(current_user).each do |country|
    display country
  end
end

But it doesn't smell very good. Specially that in the future I'll might want to add more decisions and I believe these belong to the controller.

I'm sure there is a pattern I'm missing... any hints?


Solution

  • At your controller your_condition depends on how many possible values have you for :published

    @cities = current_user.cities.where(your_condition)
    

    For example

    @cities = current_user.cities.where({published: ["published", "unpublished"]})
    

    at your view

    <% @cities.each do |c| %>
      # your code to show each city
      c
    <% end %>