Godzilla74
Godzilla74

Reputation: 2502

Rails get last X objects with attribute match

I have a model DeferredHost, which also has an attribute ignore_flag. At the present, I'm just getting all of the deferred hosts in my controller:

@deferred_hosts = @company.deferred_hosts.last(5)

However, I'd like to make it subjective and only get the last 5 deferred hosts that have the ignore_flag = true.

How can I go about doing this? Should I use an if statement and loop through each deferred host, or is there a more 'Rails' way?

Upvotes: 1

Views: 60

Answers (1)

james00794
james00794

Reputation: 1147

You can use where to make the query more specific:

@deferred_hosts = @company.deferred_hosts.where(ignore_flag: true).last(5)

Upvotes: 1

Related Questions