首页 > 解决方案 > 无法运行将用户戳添加到现有表 Rails 的迁移

问题描述

我正在使用 gem blamer 将用户戳添加到一些已经创建的表中。我尝试在创建新表时添加用户戳,它可以工作。但是我需要添加到现有表中,我不知道在迁移中要写什么。这个 gem 就像其他添加 userstamp 但只有这个似乎在 rails 6 中工作。

class User < ActiveRecord::Base
  cattr_accessor :current_user
end

class ApplicationController < ActionController::Base
  before_action :set_userstamp

  def set_userstamp
    User.current_user = User.find(session[:user_id])
  end
end
class AddUserstampsToIllustrators < ActiveRecord::Migration[6.0]
  def change
    add_column :illustrators, :userstamps
  end
end

我收到以下错误:

== 20201106193035 AddUserstampsToIllustrators: migrating ======================
-- add_column(:illustrators, :userstamps)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

wrong number of arguments (given 2, expected 3)
/home/morganaborges/code/MorganaTBorges/bamboleio_project/db/migrate/20201106193035_add_userstamps_to_illustrators.rb:3:in `change'
/home/morganaborges/code/MorganaTBorges/bamboleio_project/bin/rails:9:in `<top (required)>'
/home/morganaborges/code/MorganaTBorges/bamboleio_project/bin/spring:15:in `<top (required)>'
./bin/rails:3:in `load'
./bin/rails:3:in `<main>'

Caused by:
ArgumentError: wrong number of arguments (given 2, expected 3)
/home/morganaborges/code/MorganaTBorges/bamboleio_project/db/migrate/20201106193035_add_userstamps_to_illustrators.rb:3:in `change'
/home/morganaborges/code/MorganaTBorges/bamboleio_project/bin/rails:9:in `<top (required)>'
/home/morganaborges/code/MorganaTBorges/bamboleio_project/bin/spring:15:in `<top (required)>'
./bin/rails:3:in `load'
./bin/rails:3:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

标签: ruby-on-rails

解决方案


查看https://github.com/infused/blamer,默认情况下,两列是 created_by 和 updated_by 类型为整数。所以...

add_column :illustrators, :created_by, :integer
add_column :illustrators, :updated_by, :integer

(整数在https://github.com/infused/blamer/blob/master/lib/blamer/userstamp.rb#L47中使用)


推荐阅读