ruby - 与 Ruby、Redis 和 Ohm 的多对多关系

标签 ruby redis ohm

我正在尝试使用 Ohm 在 Redis 中创建多对多关系。例如,我将 Book 和 Author 模型定义如下:

class Book < Ohm::Model
  attribute :title
  set :authors, Author
end

class Author < Ohm::Model
  attribute :last_name
  attribute :first_name
  set :books, Book
end

我希望能够做的是利用 Ohm 的索引功能来进行查找,例如:

require 'test_helper'

class ManyToManyRelationshipTest < ActiveSupport::TestCase

  setup do
    @dave_thomas = FactoryGirl.build(:dave_thomas)
    @andy_hunt = FactoryGirl.build(:andy_hunt)
    @chad_fowler = FactoryGirl.build(:chad_fowler)

    @pick_axe = FactoryGirl.build(:pick_axe)
    @pick_axe.authors << @dave_thomas 
    @pick_axe.authors << @andy_hunt
    @pick_axe.authors << @chad_fowler

    @thinking_and_learning = FactoryGirl.build(:pragmatic_thinking_and_learning)
    @thinking_and_learning.authors << @andy_hunt
  end

  test "find a Book by Author" do
    assert Book.find(:author_id => @andy_hunt.id).include?(@pick_axe)
    assert Book.find(:author_id => @andy_hunt.id).include?(@thinking_and_learning)
  end

  test "find Authors by Book" do
    assert Author.find(:book_id => @pick_axe.id).include?(@dave_thomas)
    assert Author.find(:book_id => @pick_axe.id).include?(@andy_hunt)
    assert Author.find(:book_id => @pick_axe.id).include?(@chad_fowler)
  end
end

使用上面的代码,我得到以下异常: Ohm::Model::IndexNotFound:索引:未找到 author_id。 (当试图找到给定作者的书籍时)

我已尝试按照此处所述构建自定义索引:http://ohm.keyvalue.org/examples/tagging.html ,这里:http://pinoyrb.org/ruby/ohm-inside-tricks

不幸的是,索引似乎是在首次创建模型时构建的,这意味着 Set 是空的(因为,如果我理解正确的话,在为模型分配 ID 之前,Sets 在 Ohm 中不可用)。

非常感谢任何帮助或建议!

最佳答案

这种情况下的解决方案不太自动化:

require "ohm"

class Book < Ohm::Model
  attr_accessor :authors

  attribute :title

  index :authors
end

class Author < Ohm::Model
  attribute :name
end

###

require "test/unit"

class BooksTest < Test::Unit::TestCase
  def test_books_by_author
    dave = Author.create(name: "Dave")
    andy = Author.create(name: "Andy")
    dhh = Author.create(name: "DHH")

    pickaxe = Book.create(title: "Pickaxe", authors: [dave.id, andy.id])

    assert_equal pickaxe, Book.find(authors: dave.id).first
    assert_equal pickaxe, Book.find(authors: andy.id).first

    assert_equal nil, Book.find(authors: dhh.id).first
  end
end

有道理吗?

关于ruby - 与 Ruby、Redis 和 Ohm 的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7967004/

相关文章:

ruby - 如何在 ruby​​ 中代理 shell 进程

ruby - 我怎样才能摆脱这个 ruby 警告?

ruby - 是否可以使用 Ohm 更新模型属性并且 Redis DB 是 Ruby?

ruby - 检索/列出 Redis 数据库中的所有键/值对

ruby - 覆盖欧姆模型的属性

ruby - 包裹在 _() 中的 Ruby 字符串是什么意思?

ruby - 是否有 ruby​​ 方法可以在其他字符串之间选择字符串?

nosql - 存储非平稳分布的数据库

linux - 如何在 initContainer 中使用 netcat ping 受密码保护的 Redis 服务器?

Redis 和 Asp.Net session 状态 - Eval 超时