主键跟随我

时间:2014-01-07 19:48:36

标签: ruby-on-rails

我有一个表,其中主键是auto_increment id。我有一个简单的代码来从表中检索世界:

 Server.select('world')

但是对于世界列表,我得到了所有世界的空主键ID,输出如下:

[{"world":"Sandbox","id":null},{"world":"CogitoR4","id":null},{"world":"CarnageR4","id":null},{"world":"Theos","id":null},{"world":"AmberR4","id":null},{"world":"DedalR2","id":null},{"world":"HiTech152","id":null},{"world":"Davids152","id":null},{"world":"Magnus152","id":null}]

我如何解决这个问题?

表:

CREATE TABLE IF NOT EXISTS `servers` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `players` int(4) NOT NULL,
  `maximum` int(4) NOT NULL,
  `online` tinyint(1) NOT NULL,
  `ip` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `port` int(5) NOT NULL DEFAULT '25565',
  `server_type` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `world` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `map` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `server` (`name`),
  KEY `ip` (`ip`)
)

2 个答案:

答案 0 :(得分:0)

首先,我创建一个名为Server

的示例模型
% rails g model server world:string foo:string bar:string

迁移数据库

% rake db:migrate

启动控制台并创建一些示例数据

% rails c
> Server.create world: "hello", foo: "a", bar: "a"
> Server.create world: "sample", foo: "b", bar: "b"

仅选择world字段

> Server.select(:world)
# SELECT world FROM "servers"
# => [#<Server world: "hello">, #<Server world: "sample">]

选择worldid字段

> Server.select(:world).select(:id)
# SELECT id, world FROM "servers"
# => [#<Server id: 1, world: "hello">, #<Server id: 2, world: "sample">]

注意:尚未选择foobar字段


它甚至适用于.to_json电话

> Server.select(:world).to_json
# SELECT world FROM "servers"
# => "[{\"world\":\"hello\"},{\"world\":\"sample\"}]"

您可以在其他条件下进行链接以缩小选择范围

> Server.where(foo: "a").select(:world)
# Server Load (0.2ms)  SELECT world FROM "servers" WHERE "servers"."foo" = 'a'
# => [#<Server world: "hello">]

答案 1 :(得分:0)

您应该使用.pluck方法:

Server.pluck(:world)

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck