如何以2的幂递增键值

时间:2016-06-20 16:11:55

标签: ruby ruby-datamapper

我对将多个值存储在一个列中感兴趣,而不是使用传统的多对多表:

class Beer
  include DataMapper::Resource

  property :id, Serial
  property :name, String
  property :containers, Integer # use bit arithmetic to store multiple values

  validates_presence_of :name, :containers

end

class Container
  include DataMapper::Resource

  property :id, Serial # increment in powers of two?
  property :name, String
  property :volume, Integer

  validates_presence_of :name, :volume

end

容器:

ID  Name    Volume  Unit
1   Growler 64      oz
2   Cowler  32      oz
4   Bomber  750     mL
8   Six-fifty  650  mL
16  4 pack  64      oz
32  6 pack  72      oz

啤酒:

ID  Name Containers
1   LSD  72
2   Düo  16

是否有一种简单的方法来配置DataMapper资源以增加2的幂的串行值?我假设这种关联将成为一种挑战。

1 个答案:

答案 0 :(得分:2)

您不能使用Serial属性类型执行此操作,但可以使用整数和before :create挂钩:

class Container
  include DataMapper::Resource

  property :id, Integer, key: true # Use whatever options you like
  property :name, String
  property :volume, Integer

  validates_presence_of :name, :volume

  # Create a new id based on the last element
  before :create do |c|
    last_container = Container.last
    # If integer has N bits, then you can only store N containers in your database (normally, 32 or 64 bits).
    c.id = last_container ? (last_container.id * 2) : 1
  end
end

无论如何,您应该使用关系模型,而不是使用此 hacky-tricks ,因为有人已对您的帖子发表了评论。它比这种解决方案更易于维护,易于阅读和简单。

哦,顺便说一句,如果您需要快速访问数据库,请查看Graph databasesneo4jrbNeo4j的OGM。