I have a table named Player in my Rails app, and on the table, there are seven boolean attributes.
monday: true, tuesday: false, wednesday: true, thursday: false, friday: false, saturday: true, sunday: false
What is the best way to return an array with all the days that are true with ActiveRecord? I want to return:
["monday", "wednesday", "saturday"]
Any ideas on an efficient way to do this? I am drawing a blank? Player.first.map?
Assuming you mean that there are 7 attributes on the model you could add a method to
PlayerlikeSo for your example it would just be
This is making use of the ActiveRecord
attributesmethod on a model instance which returns aHashof attribute names to values.As InternetSeriousBusiness has commented, there is already an array of the day names defined on the
Dateclass so you could use that and avoid listing the days yourself, but note that the days in there start with an initial capital letter so you’d need adowncaseto match your attribute names e.g.