一尘不染

与Ruby,Redis和Ohm的多对多关系

redis

我正在尝试使用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为空(因为,如果我理解正确的话,Set必须在为模型分配ID之前在Ohm中不可用)。

我真的很感谢任何帮助或建议!


阅读 278

收藏
2020-06-20

共1个答案

一尘不染

这种情况下的解决方案自动化程度较低:

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

说得通?

2020-06-20