我正在尝试在我的 Rails 应用程序上安装回形针 gem,我连续遇到了 3 个问题,我想向他们指出,这可能与最后一个问题有关:
1-我无法安装回形针依赖项“mimemagic”=>我通过将文件
freedesktop.org.xml.in
及其变量FREEDESKTOP_MIME_TYPES_PATH
添加到我的Windows计算机来解决它。
2 - 然后在初始化回形针后,我无法进行迁移=>我通过添加我的rails应用程序的版本来解决它,该版本是[6.1] bessid活动记录,所以它变成
class AddAttachmentImageToPics < ActiveRecord::Migration[6.1]
。
3-我遇到的最后一个问题是当我输入
rails db:migrate
时,我收到一条消息:
ArgumentError: wrong number of arguments (given 3, expected 2)
这是我的迁移文件的内容:
class AddAttachmentImageToPics < ActiveRecord::Migration[6.1]
def self.up
change_table :pics do |t|
t.attachment :image
end
end
def self.down
remove_attachment :pics, :image
end
end
cmd 中的消息:
C:\Users\Admin\Desktop\Ruby\instagrameme>rails db:migrate
== 20220205102326 AddAttachmentImageToPics: migrating =========================
-- change_table(:pics)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
wrong number of arguments (given 3, expected 2)
C:/Users/Admin/Desktop/Ruby/instagrameme/db/migrate/20220205102326_add_attachment_image_to_pics.rb:4:in `block in up'
C:/Users/Admin/Desktop/Ruby/instagrameme/db/migrate/20220205102326_add_attachment_image_to_pics.rb:3:in `up'
Caused by:
ArgumentError: wrong number of arguments (given 3, expected 2)
C:/Users/Admin/Desktop/Ruby/instagrameme/db/migrate/20220205102326_add_attachment_image_to_pics.rb:4:in `block in up'
C:/Users/Admin/Desktop/Ruby/instagrameme/db/migrate/20220205102326_add_attachment_image_to_pics.rb:3:in `up'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
使用 kt-paperclip,它是相同的回形针宝石,但由 https://github.com/kreeti
对于猴子修补,您需要创建两个文件(我真的推荐您),或者如果您想将所有文件保留在同一个文件中,则只需创建一个文件
第一个
config/initializers/paperclip_attachment_patch.rb
module Paperclip
module Schema
module TableDefinition
def attachment(*attachment_names)
options = attachment_names.extract_options!
attachment_names.each do |attachment_name|
COLUMNS.each_pair do |column_name, column_type|
column_options = options.merge(options[column_name.to_sym] || {})
column("#{attachment_name}_#{column_name}", column_type, **column_options)
end
end
end
end
end
end
还有第二个
config/initializers/paperclip_validators_patch.rb
module Paperclip
module Validators
class AttachmentContentTypeValidator < ActiveModel::EachValidator
def mark_invalid(record, attribute, types)
record.errors.add attribute, :invalid, **options.merge(types: types.join(', '))
end
def validates_attachment_content_type(*attr_names)
options = _merge_attributes(attr_names)
validates_with AttachmentContentTypeValidator, **options.dup
validate_before_processing AttachmentContentTypeValidator, **options.dup
end
end
end
end
正如 @Cameron 上面所说,在
ruby >= 2.7
上删除了哈希到关键字参数的转换,因此为了解决这个问题,您只需使用 **
到哈希参数中,在我们的场景中,我们在 **column_options
和 上进行了操作**options