在 Rails 4.1 中,如何通过枚举符号查找记录? [英] In Rails 4.1, how to find records by enum symbol?

查看:28
本文介绍了在 Rails 4.1 中,如何通过枚举符号查找记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个模型:

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

如何在不使用枚举的数值或无需遍历每个对话的情况下找到所有活动对话?

How can I find all active conversations without using the numeric value of the enum or without having to iterate over each conversation?

我尝试了 Conversation.where(status: :active),但没有产生任何结果.

I tried doing Conversation.where(status: :active), but it didn't yield any results.

想到的唯一解决方案是遍历所有对话并选择活动对话,但这看起来不是一个好的解决方案.

The only solution comes to mind is to iterate over all conversations and select the active ones, but it doesn't look like a good solution.

Conversation.all.select {|conversation| conversation.active? }  

我能对此做些什么吗?

推荐答案

ActiveRecord::Enum 根据其值提供范围.

试试吧:

Conversation.active

Conversation.archived

当然,您可以创建自己的范围,如 Kyle Decot 所述.

Of course, you can create your own scopes as Kyle Decot mentioned.

这篇关于在 Rails 4.1 中,如何通过枚举符号查找记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆