PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

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

 October 21, 2022     has-many, oop, ruby-on-rails     No comments   

Issue

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 %>


Answered By - Oscar Luza
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing