如何按 2 的幂递增键值
How to increment key values by power of two
我有兴趣在单个列中存储多个值,而不是使用传统的多对多 table:
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 次幂?我假设协会将是一个挑战。
你不能用 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,因为有人已经评论过您的 post。它比这种解决方案更易于维护、更易于阅读和简单。
哦,顺便说一句,如果你需要快速访问你的数据库,你应该看看Graph databases and neo4jrb, an OGM for Neo4j。
我有兴趣在单个列中存储多个值,而不是使用传统的多对多 table:
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 次幂?我假设协会将是一个挑战。
你不能用 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,因为有人已经评论过您的 post。它比这种解决方案更易于维护、更易于阅读和简单。
哦,顺便说一句,如果你需要快速访问你的数据库,你应该看看Graph databases and neo4jrb, an OGM for Neo4j。