2011-11-01 3 views
0

um을 사용하여 Redis에서 다 대다 관계를 만들려고합니다. 예를 들어, 나는 다음과 같이 도서 및 저자 모델 정의가 : 내가 좋아하는 것이 무엇Ruby, Redis 및 Ohm과의 다 대다 관계

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

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

이 할 수있는 활용 옴의 인덱싱 기능이다 할 수 있기는 발견과 같은 다음으로

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 : index : author_id not found. (책을 발견 할 때 저자가 주어)

여기에 설명 된 바와 같이 나는 사용자 정의 인덱스를 구축하려고했습니다

: http://ohm.keyvalue.org/examples/tagging.html, 여기 : 모델이 처음 인 경우 인덱스가 내장되어 같은 http://pinoyrb.org/ruby/ohm-inside-tricks

불행하게도, 보이는 만든, 즉 집합이 비어 있음을 의미합니다 (모델에 ID가 할당 될 때까지 Ohm에서 Sets를 사용할 수 없기 때문에 정확하게 이해할 수 있습니다).

정말 도움이나 제안에 감사드립니다!

답변

3

이 경우, 해결책은 다소 덜 자동이다

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 

말이?

+0

완벽한 의미로 - 정말 고마워요! – wmkoch