ruby-on-rails - rspec 序列化哈希 - 查询记录为空

标签 ruby-on-rails rspec sqlite

我有一个名为“内容”的模型,其中有一个名为“依赖项”的列,序列化为哈希:

class Content < ActiveRecord::Base
  attr_accessible :dependencies
  serialize :dependencies, Hash
end

在过去的几个小时里,这真的让我神经紧张。我将不胜感激任何帮助/提示。

问题:

  • 迁移中的默认(空)值应该是什么?
  • FactoryGirl 中的默认(空)值应该是什么?
  • 最重要的是 - 如何查询以查找空值?

提前致谢!

最佳答案

What should be the default (empty) value in migration? What should be the default (empty) value in FactoryGirl?

在这两种情况下,空哈希 {}

Most important - how to query in order to find empty values?

由于序列化值是使用 YAML 存储的,因此您需要按如下方式搜索:

Content.where('dependencies = ?', {}.to_yaml)

这是我对上述内容进行测试的 irb 转录:

MacbookAir1:so1 palfvin$ rails c
Loading development environment (Rails 4.0.0)
2.0.0-p247 :001 > u = User.new(role: {})
 => #<User id: nil, role: {}, role2: nil> 
2.0.0-p247 :002 > u.save
   (0.3ms)  begin transaction
  SQL (3.3ms)  INSERT INTO "users" ("role", "role2") VALUES (?, ?)  [["role", "--- {}\n"], ["role2", nil]]
   (1.1ms)  commit transaction
 => true 
2.0.0-p247 :003 > u.role
 => {} 
2.0.0-p247 :004 > {}.to_yaml
 => "--- {}\n" 
2.0.0-p247 :005 > u
 => #<User id: 4, role: {}, role2: nil> 
2.0.0-p247 :006 > User.where(role: {}.to_yaml)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."role" = '--- {}
'
 => #<ActiveRecord::Relation [#<User id: 3, role: {}, role2: nil>, #<User id: 4, role: {}, role2: nil>]> 
2.0.0-p247 :007 > 

(注意:在发布此答案的第一个版本之前,我已经创建了一个 User 实例 (#3),这就是它也出现在我的 where 中的原因)。

这是我的 user.rb 文件:

class User < ActiveRecord::Base

    has_many :who_rated_comment_rels, foreign_key: "user_id", dependent: :destroy
    serialize :role, Hash
    serialize :role2

end

您可以忽略与您的案例无关的内容(即除角色之外的任何内容)。我出于各种 StackOverflow 目的而破解了这个项目。

关于ruby-on-rails - rspec 序列化哈希 - 查询记录为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20757596/

相关文章:

ruby-on-rails - 在 rails_root/Incron 之外运行 rake 不会为 rails 运行 rake 或 bundle 命令

ruby-on-rails - RSpec::ExampleGroups::User::Validations 的未定义方法 `validate_presence_of'

iphone - 在 iPhone 应用程序更新上将内容更新/插入到现有 Sqlite 数据库中

ruby-on-rails - 设计:尝试创建没有 ID 的记录

sqlite - sqlite 支持 linq-to-SQL 吗?

mysql - Rails/MySQL ActiveRecord::RecordNotUnique

ruby-on-rails - 为其他新操作添加路由的目的是什么?

css - act_as_taggable_on 模板/css : Rails tag cloud

ruby-on-rails - SimpleCov计算用户模型的0%覆盖率

ruby-on-rails - rails/RSpec : mail render in spec results in missing template