首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与Ruby、Redis和Ohm的多对多关系

与Ruby、Redis和Ohm的多对多关系
EN

Stack Overflow用户
提问于 2011-11-01 21:16:01
回答 1查看 1.2K关注 0票数 0

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

代码语言:javascript
复制
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的索引功能来进行查找,例如:

代码语言:javascript
复制
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: IndexNotFound: Index :author_id not found。(当试图查找给定作者的书籍时)

我尝试构建自定义索引,如下所示:http://ohm.keyvalue.org/examples/tagging.html,这里:http://pinoyrb.org/ruby/ohm-inside-tricks

不幸的是,看起来索引是在第一次创建模型时构建的,这意味着集合是空的(因为,如果我理解正确的话,集合在Ohm中是不可用的,直到模型被分配了一个ID)。

非常感谢大家的帮助和建议!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-20 22:46:10

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

代码语言:javascript
复制
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

合乎道理?

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7967004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档