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?

4

2 回答 2

3

假设您的意思是模型上有 7 个属性,您可以添加一个Player喜欢的方法

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

所以对于你的例子,它只是

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

这是attributes在模型实例上使用 ActiveRecord 方法,该方法将Hash属性名称返回到值。


正如InternetSeriousBusiness所评论的那样,已经在Date类上定义了一组日期名称,因此您可以使用它并避免自己列出日期,但请注意,其中的日期以首字母大写字母开头,因此您需要一个downcaseto匹配您的属性名称,例如

Date::DAYNAMES.select { |day| attributes[day.downcase] }
于 2012-09-24T19:02:23.720 回答
2

您可以通过以下方式解决此问题:

p = Player.first

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

希望能帮助到你。

于 2012-09-24T19:38:06.277 回答