5

使用 Ohm & Redis 时,集合与集合或列表有什么区别?

几个 Ohm 示例使用列表而不是集合(请参阅列表文档本身):

class Post < Ohm::Model
  list :comments, Comment
end

class Comment < Ohm::Model
end

这种设计选择的理由是什么?

4

2 回答 2

15

只是为了扩展 Ariejan 的答案。

  • 列表 - 有序。类似于 Ruby 中的数组。用于排队和保持物品有序。

  • Set - 一个无序列表。它的行为类似于 Ruby 中的数组,但针对更快的查找进行了优化。

  • Collection - 与reference结合使用,它提供了一种表示关联的简单方法。

本质上,集合和引用是处理关联的便捷方法。所以这:

class Post < Ohm::Model
  attribute :title
  attribute :body
  collection :comments, Comment
end

class Comment < Ohm::Model
  attribute :body
  reference :post, Post
end

是以下内容的快捷方式:

class Post < Ohm::Model
  attribute :title
  attribute :body

  def comments
    Comment.find(:post_id => self.id)
  end
end

class Comment < Ohm::Model
  attribute :body
  attribute :post_id
  index :post_id

  def post=(post)
    self.post_id = post.id
  end

  def post
    Post[post_id]
  end
end

为了回答您关于设计选择基本原理的原始问题 - 引入了集合和引用以提供一个简单的 api 来表示关联。

于 2011-06-08T16:08:03.887 回答
5

List - 元素的有序列表。当您请求整个列表时,您会按照您在列表中放置它们的方式对项目进行排序。

Collection - 元素的无序集合。当您请求收集时,项目可能会以随机顺序出现(例如无序)。**

在您的示例中,评论是有序的。

** 我知道随机与无序不同,但它确实说明了这一点。

于 2011-01-24T15:27:55.990 回答