簡體   English   中英

Rails枚舉:重寫getter始終與符號而不是字符串進行比較

[英]Rails Enum: overriding getter to always compare with symbols instead of strings

查看ActiveRecord的Enum 文檔 ,我發現不一致的是,有時允許我使用符號,有時只需要使用字符串。

在文檔中,您可以使用符號查詢:

Conversation.where(status: [:active, :archived])
Conversation.where.not(status: :active)

但是您不能使用符號進行比較:

conversation = Conversation.new(status: :active)
conversation.status # "active"
conversation.status == :active # false

您可以使用符號設置狀態,但是讀回它會返回一個字符串,因此您必須始終使用字符串進行比較:

conversation.status = :active # :active
conversation.status # "active"

我的觀點是:由於性能,我只希望使用符號,這對我來說更慣用了。 如果枚舉是使用符號定義的,並且可以使用符號查詢,那么在比較諸如conversation.status == "active"類的內容時,為什么我必須(必須記住!)使用字符串?

我的想法是重寫getter:

def status
  super.try(:to_sym)
end

這樣,我總是可以使用符號。 有任何合理的理由不這樣做嗎?

但是您不能使用符號進行比較:

conversation = Conversation.new(status: :active)
conversation.status # "active"
conversation.status == :active # false

您不需要與符號進行比較:

conversation.active? # true

有任何合理的理由不這樣做嗎?

是的,您應該使用庫的方法和模塊,而不要編寫自己的未經測試的多余代碼。

無需將枚舉與字符串或整數進行比較。 DOC鏈接

conversation = Conversation.new(status: :active)
conversation.active? #true/false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM