I'm attempting to create a many-to-many relationship in Redis using Ohm. As an example, I have Book and Author models defined as follows:
class Book < Ohm::Model
attribute :title
set :authors, Author
end
class Author < Ohm::Model
attribute :last_name
attribute :first_name
set :books, Book
end
What I would like to be able to do is leverage Ohm's indexing capabilities to do finds such as:
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
With the code above, I get the following Exception: Ohm::Model::IndexNotFound: Index :author_id not found. (when trying to find Books given an author)
I've tried to build custom indices as described here: http://ohm.keyvalue.org/examples/tagging.html, and here: http://pinoyrb.org/ruby/ohm-inside-tricks
Unfortunately, it looks like the index is built when the model is first created, which means the Set is empty (because, if I understand correctly, Sets are unusable in Ohm until the model has been assigned an ID).
I really appreciate any help or suggestions!
The solution in this case is a bit less automatic:
Makes sense?