Ruby-on-rails 在 Rails 4.1 中,如何通过枚举符号查找记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25101009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:50:51  来源:igfitidea点击:

In Rails 4.1, how to find records by enum symbol?

ruby-on-railsrubyruby-on-rails-4rails-activerecordruby-on-rails-4.1

提问by Abdulaziz

Assume I have this model:

假设我有这个模型:

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?

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

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

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

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? }  

Is there anything I can do about this?

我能做些什么吗?

回答by Kensuke Naito

ActiveRecord::Enumprovides scopes based on its values.

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

Just try:

你试一试:

Conversation.active

or

或者

Conversation.archived

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

当然,您可以像Kyle Decot提到的那样创建自己的范围。

回答by Mirror318

This works great:

这很好用:

Conversation.where("conversation.status = ?", Conversation.statuses[:active])

For some reason this does NOT work:

出于某种原因,这不起作用:

Conversation.where(status: :active) #searches for NULL
Conversation.where(status: 'active') #searches for status=0 no matter what the enum

Update

更新

All the above statements work with Rails 5. Happy coding!

以上所有语句都适用于 Rails 5。快乐编码!

回答by Kyle Decot

ActiveRecord::Enumprovides built-in scopes based on the values so you can simply do:

ActiveRecord::Enum提供基于值的内置范围,因此您可以简单地执行以下操作:

Conversation.active
Conversation.archived

回答by 6ft Dan

Conversation.where(status: Conversation.statuses[:active])

回答by Shifa Khan

Did you try Conversation.where(status: [:active, :archived])? As listed here.

你试了Conversation.where(status: [:active, :archived])吗?作为上市这里

回答by jasmo2

try this:

尝试这个:

.enum :status => {:active => "active", :archived => "archived"ok_off => "took off"}