I have a Rails4 app with the following models:

```
 1. Systems (has many devices, has many parameters through devices)
 2. Devices (belongs to a system, has many parameters)
 3. Parameters (belongs to a Device)
 4. Events (polymorphic - Systems, Devices and Parameters can have events)

```

When an event is created, a boolean field (on the event) is assigned a value. False indicated a failure.

I have a scope on my events, to only show failing events:

```
scope :failing, -> { where(okay: false).order('created_at desc') }

```

I can retrieve events as follows:

```
System.events.failing
Device.events.failing
Parameter.events.failing

```

I am trying to return a list of Systems where either:

```
1. the most recent event for the system has failed
2. the most recent event for any of it's devices has failed
3. the most recent event for any parameters of it's devices have failed

```

I have written this (horrible) SQL query which when executed in the console, returns the systems as an array:

```
"SELECT * FROM Systems WHERE Systems.id IN (SELECT Devices.system_id FROM Devices WHERE Devices.id IN (SELECT Parameters.device_id FROM Parameters JOIN EVENTS ON Parameters.id=Events.eventable_id WHERE Events.okay ='f')) OR Systems.id IN (SELECT Devices.system_id FROM Devices JOIN Events ON Devices.id=Events.eventable_id WHERE Events.okay='f')")

```

I need to either define a scope on the System model or a class method to return a list of 'failing' systems. Can you help?
['https://Stackoverflow.com/questions/24371011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2778833/']
Basically your Javascript could be shortened to:

```
$(".question").click(function(argument) {  
    $(this).parent().find(".answer").removeClass("hideinit").addClass("display");
});

```

In order to make this work the only other thing you need to do is to make `question` a class rather than as an id. That looks like:

```
<p class="answer hideinit">the answer</p>

```

**[See the fiddle here](http://jsfiddle.net/6S9r3/2/)**

---

**Edit: Add Hide / Show**

To get this to hide and show as expected you'll want to update the code to check the current class before hiding and showing. That looks like:

```
$(".question").click(function(argument) {  
    var el = $(this).parent().find(".answer");
    if (el.hasClass("display")) {
       el.removeClass("display").addClass("hideinit");
    } else {
        el.removeClass("hideinit").addClass("display");
    }
});

```

**[See the fiddle here](http://jsfiddle.net/6S9r3/3/)**
```
$(".question").on('click',function() {
    $(this).next().toggle();
});

```