如何存储和比较:符号一个ActiveRecord(Ruby on Rails的) [英] How to store and compare :symbols in an ActiveRecord (Ruby on Rails)
问题描述
我认为这将是很好的使用常量来填充一个ActiveRecord表中的状态字段。但是,当涉及到检查,如果这种状态有一个特别的状态,我有麻烦。
I thought it would be good to populate a status field in an activeRecord table using constants. However, when it comes to checking if this status has a particular status, I'm having trouble.
如果我这样做,
e = Mytable.new
e.status = :cancelled
e.save
然后refind记录,并尝试和我的状态比作象征,检查失败。我从控制台一些输出,显示这一点。
then refind the record and try and compare my status to the symbol, the check fails. I have some output from the console to show this.
irb(main):060:0> e.status.eql?("cancelled")
=> true
irb(main):061:0> e.status.eql?(:cancelled)
=> false
irb(main):062:0> e.status == :cancelled
=> false
irb(main):063:0> e.status == "cancelled"
=> true
irb(main):064:0> e.status == :cancelled.to_s
=> true
是否有持有创纪录的状态更好的办法?是否有检测的方式,如果当前字段值等于:符号而不转换:符号为字符串?我想有可能是运营商,我不知道。
Is there a better way of holding a status in a record? Is there a way of testing if a current field value is equal to the :symbol without converting the :symbol to a string? I'm thinking there may be an operator I'm not aware of.
推荐答案
目前ecoologic的要求,这里是我的评论作为一个答案:
At the request of ecoologic, here is my comment as an answer:
ecoologic可以为你很好的解决方案,但我会建议从该转向远离,使一类,在它的常量。你可以做的事情一样e.status =状态::已取消。和国内这可能是一个字符串,也没关系。你还在使用常量,它会报错了,如果该常量不存在,这是清洁的方式。
ecoologic has a good solution for you, but I would recommend steering away from this and making a class with constants in it. That you can do things like e.status = Statuses::CANCELLED. And internally that could be a string and it doesn't matter. You're still using constants, and it will error out if that constant doesn't exist, and it's cleaner that way.
这篇关于如何存储和比较:符号一个ActiveRecord(Ruby on Rails的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!