What is the difference between a collection and a set or list when using Ohm & Redis?
Several of the Ohm examples use a list rather than a collection (see the list doc itself):
class Post < Ohm::Model
list :comments, Comment
end
class Comment < Ohm::Model
end
What is the rationale for this design choice?
Just to expand on Ariejan's answer.
List - ordered. Similar to an Array in Ruby. Used for queues and keeping items ordered.
Set - an unordered list. It behaves similar to an Array in Ruby but is optimized for faster lookups.
Collection - used in conjunction with reference, it provides a simple way of representing associations.
In essence, collections and references are convenience methods for dealing with associations. So this:
class Post < Ohm::Model
attribute :title
attribute :body
collection :comments, Comment
end
class Comment < Ohm::Model
attribute :body
reference :post, Post
end
is a shortcut for the following:
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
To answer you original question about the rationale for the design choice - collections and references were introduced to provide a simple api for representing associations.
List - ordered list of elements. When you request the entire list, you get the items ordered the way you put them in the list.
Collection - unordered collection of elements. When you request the collection, items may appear in random order (e.g. unordered).**
In your example, comments are ordered.
** I know that random is not the same as unordered, but it does illustrate the point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With