How to represent a list in Datamapper
I have the following datamapper model:
class List
include DataMapper::Resource
property :id, Serial
property :author, String, :required => true,
:default => lambda { |r, p| @user_nick }
property :name, String, :required => true, :length => 1..255
property :created_at, DateTime, :default => lambda{ |r, p| Time.now }
has n, :items
end
class Item
include DataMapper::Resource
property :id, Serial
property :text, String, :required => true, :length => 1..255
belongs_to :list
end
In other words, a list that contains zero or more items.
The list is not yet ordered. My question is: how do I make that happen? The two obvious solutions I see are to either
(a) augment Item
with an index
integer or
(b) augment Item
with a previous
and next
field, IOW implement a doubly linked list.
Both solutions strike me as inefficient and bug-prone (I haven't implemented a linked list o开发者_运维知识库r traversal and modification operations for years, and even then it was a school exercise).
Is there a better way? (I'm not particular about performance, this is just a prototype and not a real application, but I'd like to get a 'proper' solution both in terms of robustness and in terms of performance). If it matters, I am using the AppEngine backend of Datamapper, but I'd like something that could also work well on a RDBMS.
Cheers
(a) Whilst I agree that it can be bug prone when done manually, dm-is-list takes care of some of the details. Careful coding when updating many items at once (see: optimum scenario) is required.
(b) Although I can't comment on how this relates to AppEngine, RDBMS systems give you random access, and as such, a doubly linked list isn't required. On a side note, sorting, reordering & navigating a doubly linked list in a RDBMS scares me. I prefer that my app fails rather than the possibility of an infinite loop.
精彩评论