2

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?

1
  • Pls. tell the structure of Player table/ the table in which monday:true ... data is there a little bit more.. Commented Sep 24, 2012 at 19:02

2 Answers 2

3

Assuming you mean that there are 7 attributes on the model you could add a method to Player like

def days
  ["monday", "tuesday", "wednesday", "thursday", "friday", 
    "saturday", "sunday"].select { |day| attributes[day] }
end

So for your example it would just be

Player.first.days # => e.g. ["monday", "wednesday", "saturday"]

This is making use of the ActiveRecord attributes method on a model instance which returns a Hash of attribute names to values.


As InternetSeriousBusiness has commented, there is already an array of the day names defined on the Date class 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 a downcase to match your attribute names e.g.

Date::DAYNAMES.select { |day| attributes[day.downcase] }
Sign up to request clarification or add additional context in comments.

1 Comment

You can use Date::DAYNAMES as well.
2

You can solve this issue with something like:

p = Player.first

p.attributes.select{|k,v| v == true}.keys

Hope it helps.

1 Comment

What if you add boolean column playing in players table?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.