Ruby on rails 为什么此作用域为枚举返回错误的对象?

Ruby on rails 为什么此作用域为枚举返回错误的对象?,ruby-on-rails,activerecord,ruby-on-rails-4,Ruby On Rails,Activerecord,Ruby On Rails 4,在我的Post.rb模型中,我有: class Post < ActiveRecord::Base belongs_to :user enum is_published: [ :no, :yes ] scope :published, -> { where( is_published: "yes") } scope :unpublished, -> { where( is_published: "no") } end 同样有趣的是,我的Post表中的1条记录

在我的Post.rb模型中,我有:

class Post < ActiveRecord::Base
  belongs_to :user
  enum is_published: [ :no, :yes ]

  scope :published, -> { where( is_published: "yes") }
  scope :unpublished, -> { where( is_published: "no") }
end
同样有趣的是,我的Post表中的1条记录已经发布:yes永远不会返回

如图所示:

 > p = Post.first
  Post Load (0.4ms)  SELECT  "posts".* FROM "posts"   ORDER BY "posts"."id" ASC LIMIT 1
 => #<Post id: 1, title: "Fire at Bible College in Christian", photo: nil, body: "A massive fire is now raging at the Bible College ...", created_at: "2014-08-28 08:06:19", updated_at: "2014-09-18 20:56:32", user_id: 1, ancestry: nil, file: nil, status: 0, slug: "fire-at-bible-college-in-christian", is_published: 1, has_eyewitness: true> 
 > p.is_published
 => "yes" 
检查文档将显示适用于您的作用域的以下语法:

class Post < ActiveRecord::Base
  belongs_to :user
  enum is_published: [ :no, :yes ]

  scope :published, -> { where( is_published: Post.is_publisheds[:yes] ) }
  scope :unpublished, -> { where( is_published: Post.is_publisheds[:no]) }
end
您的查询显示您得到0表示“是”,这看起来不正确。通过这项建议的更改,您应该获得正确的“是”和“否”枚举值。另外,文档中还附带说明:

其中,枚举属性上的条件必须使用 枚举

tldr;是否发布:[:是,:否]不适合使用枚举

这个枚举和使用它的作用域有很多错误

首先,你不能用那种方式。您完全避开了枚举,只是对列进行了查询。Rails将查询值转换为整数,因为您是针对整数列进行查询的。是和否都转换为整数0,因此这些作用域无法工作。如果要使用where,则需要手动生成正确的整数值。对于您的模型,它看起来是这样的:

Post.where(is_published: Post.is_publisheds['yes'])
第二,注意is_出版的非常尴尬的多元化;这是一个提示,表明您正在为枚举使用一个坏名称

第三,您正在手动创建冗余作用域。Rails已经为枚举中的每个值提供了作用域,但是您选择了非常糟糕的名称。您的模型现在有是和否范围!您可以使用Post.yes和Post.no来获取已发布/未发布的记录,但这显然是非常错误的

这一切都源于这样一个事实,即您基本上已经枚举了一个布尔值。这完全没有抓住要点。如果您真的只需要一个布尔值,enum是不合适的,您不应该使用它。只需使用一个布尔列,编写一对sane作用域,其中whereis_published:true和whereis_published:false

如果要使用枚举,而不是使用is_published,请使用枚举状态:[:published,:unpublished],甚至使用枚举发布状态:[:published,:unpublished]。这就是你所需要的。Rails将查看枚举值,并为您生成所需的两个作用域,而无需您做额外的工作

整个类如下所示:

class Post < ActiveRecord::Base
  belongs_to :user
  enum status: [ :published, :unpublished ]
  # No need for scopes, enum gives you published/unpublished scopes already
end

是否发布[:是]将是一个错误;这是is_Published,该栏目名称的复数版本。感谢您不仅纠正了我的错误,还解释了我的错误。这是我一直在努力解决的问题,所以我错误地使用它也就不足为奇了。我做这件事的时候确实感觉不对,你的建议很有道理。多谢!所以有了enum状态,我就可以简单地做Post.published了?正当还有Post.where:published以获取所有已发布的帖子?
Post.where(is_published: Post.is_publisheds['yes'])
class Post < ActiveRecord::Base
  belongs_to :user
  enum status: [ :published, :unpublished ]
  # No need for scopes, enum gives you published/unpublished scopes already
end