4

我正尝试在Rails 5.2中使用Active Storage。我发现,我应该在迁移file类型创建领域,但我有一个错误:无法在Rails中使用ActiveStorage创建文件字段

$ rdm 
Running via Spring preloader in process 40193 
== 20171217191942 CreateDishes: migrating 
===================================== 
-- create_table(:dishes) 
rake aborted! 
StandardError: An error has occurred, this and all later migrations canceled: 

undefined method `file' for #<ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition:0x00007fd56e297750> 
/Users/alder/Projects/_apps/service_exchange/rails-backend/db/migrate/20171217191942_create_dishes.rb:6:in `block in change' 
/Users/alder/Projects/_apps/service_exchange/rails-backend/db/migrate/20171217191942_create_dishes.rb:3:in `change' 
-e:1:in `<main>' 

迁移:

class CreateDishes < ActiveRecord::Migration[5.2] 
    def change 
    create_table :dishes do |t| 
     t.string :name, index: true 
     t.string :description 
     t.file :image 

     t.timestamps 
    end 
    end 
end 

我试图创建字符串字段,但它不工作。

找不到关于在official docs

我有主动式存储迁移和我通过什么好的

+1

我很确定在rails迁移中没有这样的数据类型'文件',请尝试使用f.string –

+1

检查此博客:https://rubyinrails.com/2017/07/21/rails-introduces-active- storage-for-file-uploads/ –

+0

所以,是的,我使用了那个链接。如果你创建字符串字段,它会在稍后显示类型不匹配。 – zishe

回答

10

相反,你需要在自己的迁移创建一个专用领域的一个文件(t.file :image)主动存储使用两个表,你setuprails active_storage:install。 当您建立storage.yml你应该能够使用

has_one_attached :image 
Dishes模型中

,而无需创建image列。

+0

我认为我可能不应该为图像创建任何字段,稍后我会检查它,但我猜这是正确的答案。 – zishe

+0

是的,你是对的,谢谢你的回答! – zishe

4

您可以检查这个问题,因为(ActiveRecord field type)没有任何类型的像file如果你需要上传你可以用string类型创建像t.string