【问题标题】:Rails: How can I retrieve values from columns named `id`?Rails:如何从名为“id”的列中检索值?
【发布时间】:2023-03-21 15:40:01
【问题描述】:

使用Rails 4.2.6。我有一张这样的表格(请原谅奇怪的表格和字段命名——它们来自一个古老的非 Rails 项目):

mysql> desc user;
+-----------------+---------------------+------+-----+-----------+----------------+
| Field           | Type                | Null | Key | Default   | Extra          |
+-----------------+---------------------+------+-----+-----------+----------------+
| ...             | ...                 | ...  | ... | ...       | ...            |
| id_number       | int(10) unsigned    | NO   | PRI | NULL      | auto_increment |
| id              | varchar(128)        | NO   | UNI | NULL      |                |
| ...             | ...                 | ...  | ... | ...       | ...            |
+-----------------+---------------------+------+-----+-----------+----------------+
16 rows in set (0.00 sec)

id 字段包含标识用户的字符串,例如 "alea12"。 我的这个表的模型如下:

class User < ActiveRecord::Base
  self.table_name = 'user'
  self.primary_key = 'id_number'
end

当我尝试使用ActiveRecord 检索User.id 时,它不允许我这样做。 在 MySQL 中:

mysql> select id_number, id from user where id = "alea12" \G
*************************** 1. row ***************************
id_number: 15966
       id: alea12
1 row in set (0.00 sec)

rails c:

[1] pry(main)> User.where(id: "alea12")
  User Load (0.9ms)  SELECT `user`.* FROM `user` WHERE `user`.`id` = 'alea12'
  User Load (0.9ms)  SELECT `user`.* FROM `user` WHERE `user`.`id` = 'alea12'
=> [#<User:0x007f79c4bfe8a8
  id_number: 15966,
  id: 15966,
  ...,
  updated_date: nil>]

我希望id 字段为“alea12”,但它返回的整数与id_number 相同。 是否有任何选项可以像这样从名为 id 的列中检索值?

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    要完成此操作,您必须覆盖 ActiveRecordPrimaryKey 模块中与id 相关的所有这些公共方法。 See this

    所以不要浪费您的时间编写迁移并将您的所有 id_number 数据转移到 id ,反之亦然。

    PS:使用id 作为主键是Rails 中的最佳实践!

    谢谢

    【讨论】:

      猜你喜欢
      • 2011-04-17
      • 1970-01-01
      • 2015-01-16
      • 2012-01-06
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      相关资源
      最近更新 更多