ActiveRecord认为我使用的是整数,但我不是

时间:2019-08-28 22:47:55

标签: mysql ruby-on-rails activerecord

Rails 5.2.3
MySQL gem (mysql server is version 8)

我不想使用自动生成的ID进行迁移。在app / models / concerns / shared.rb中:

module Shared
  extend ActiveSupport::Concern
  def generate_unique_string_id_for_model
    self.id = "#{Time.now.to_f.to_s.gsub(".","_")}_#{self.class.name}" if self.id.blank?
    # Sample output: 1566326250_176106_Role
  end
end

在我的app / models / roles.rb中:

class Role < ApplicationRecord
  include Shared
  audited
  belongs_to :user
  before_create :generate_unique_string_id_for_model
end

角色的迁移文件为:

class CreateRoles < ActiveRecord::Migration[5.2]
  def change
    create_table :roles, id: false do |t|
      t.string :id, primary_key: true, null: false
      t.string :user_id
      t.string :group
      t.string :flag
      t.string :scope

      t.timestamps
    end
  end
end

我开始了一个控制台会话,并且做到了:

User.all.each do |user|
  Role.create!({'user_id':user.id.to_s,'group':'admin'})
end

我收到以下错误消息:

User Load (0.3ms)  SELECT `users`.* FROM `users`
 (0.2ms)  BEGIN
User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = '1566949867_890124_User' LIMIT 1
Role Create (0.3ms)  INSERT INTO `roles` (`id`, `user_id`, `group`, `created_at`, `updated_at`) VALUES ('1567031932_3901272_Role', '1566949867_890124_User', 'admin', '2019-08-28 22:38:52', '2019-08-28 22:38:52')
 (1.3ms)  ROLLBACK
Traceback (most recent call last):
    3: from (irb):19
    2: from (irb):19:in `rescue in irb_binding'
    1: from (irb):20:in `block in irb_binding'
ActiveModel::RangeError (15670319323901272 is out of range for ActiveModel::Type::Integer with limit 4 bytes)

如果我接受声明:

INSERT INTO `roles` (`id`, `user_id`, `group`, `created_at`, `updated_at`) VALUES ('1567031932_3901272_Role', '1566949867_890124_User', 'admin', '2019-08-28 22:38:52', '2019-08-28 22:38:52')

登录到MySQL服务器,并直接执行它,它执行时没有任何错误。

任何想法可能是什么问题?

解决方案:

事实证明,问题出在经过审核的宝石上。假定模型id是整数。我修改了迁移文件以供审核,然后将期望模型为整数的位置更改为字符串

0 个答案:

没有答案