Ohm&Redis:何时使用设置,列表或集合?
-
23-10-2019 - |
题
使用OHM和REDIS时,集合和集合或列表有什么区别?
几个欧姆示例使用列表而不是集合(请参阅 列出文档本身):
class Post < Ohm::Model
list :comments, Comment
end
class Comment < Ohm::Model
end
这种设计选择的理由是什么?
解决方案
列表 - 订购 列表 元素。当您请求整个列表时,您会以将其放入列表中的方式订购的项目。
收集 - 无序 收藏 元素。当您要求集合时,项目可能会随机顺序出现(例如无序)。**
在您的示例中,评论被订购。
**我知道随机与无序不同,但确实说明了这一点。
其他提示
只是为了扩展Ariejan的回答。
列表 - 订购。类似于Ruby中的阵列。用于队列和保持订购的物品。
设置 - 无序列表。它 行为 类似于Ruby中的数组,但已针对更快的查找进行了优化。
收集 - 与 参考, ,它提供了一种简单的表示关联的方式。
从本质上讲,收集和参考是处理关联的便利方法。所以这:
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来代表关联。
不隶属于 StackOverflow