ActiveRecord thinks I'm using an integer, but I am not

末鹿安然 提交于 2019-12-24 20:00:09

问题


Rails 5.2.3
MySQL gem (mysql server is version 8)

I do not want to use the automatically generated id, for migrations. In 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

In my app/models/roles.rb:

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

The migration file for roles is:

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

I started a console session, and did:

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

I got the following error message:

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)

If I take the statement:

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')

log into the MySQL server, and execute it directly, it executes without any errors.

Any ideas what the problem might be?

SOLUTION:

It turns out the problem is the audited gem. It assumes that the model id is an integer. I modified the migration file for audited, and changed the places where it expects the model to be an integer, to a string

来源:https://stackoverflow.com/questions/57700909/activerecord-thinks-im-using-an-integer-but-i-am-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!