如何破坏Ruby on Rails中Paperclip错误创建的列

don*_*key 8 ruby-on-rails paperclip

正如标题所示,我不小心在模型中添加了一些随机附件列.说我做了rails generate paperclip portfolio href

如何删除创建的列?rails destroy paperclip portfolio href似乎没有工作!

don*_*key 6

我创建了一个迁移文件并将内容更改为:

class RemoveAttachmentHrefToPortfolios < ActiveRecord::Migration   
  def self.up
    remove_attachment :portfolios, :href   
  end

  def self.down
    remove_attachment :portfolios, :href   
  end 
end
Run Code Online (Sandbox Code Playgroud)

问题是这不是优雅和正确的方法.我希望有人能改进这个答案..


abd*_*una 6

对于最新版本的rails 4 ++
只需创建一个迁移
示例:

rails g migration remove_attachment_photo_to_course
然后打开迁移文件

class RemoveAttachmentPhotoToCourse < ActiveRecord::Migration                                                                                                                                                                             
  def change                                                                                                                                                                                                                                   
    remove_attachment :courses, :photo                                                                                                                                                                                                   
  end                                                                                                                                                                                                                              
end
Run Code Online (Sandbox Code Playgroud)

然后运行,以更新表

rake db:migrate 
Run Code Online (Sandbox Code Playgroud)

其中:
照片是您要删除的回形针附件
的名称,课程名称是表名称


Chl*_*loe 1

通常对于您运行的迁移rake db:rollback。由于这是一个生成器,您只需手动编辑表格并删除列。

alter table portfolio drop column href_content_type;
alter table portfolio drop column href_file_name;
-- ... etc for each of the Paperclip columns.
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个迁移来删除列,但这将是矫枉过正,除非您的整个团队也运行生成器或者您签入 schema.rb 并且其他人也运行它。

以下是删除列的迁移示例:

class RemoveMagazineFromBooks < ActiveRecord::Migration
  def change
    # This is not used ANYWHERE...
    if column_exists? :refinery_books, :magazine
      remove_column :refinery_books, :magazine
      remove_index :refinery_books, :magazine if index_exists? :refinery_books, :magazine
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

请注意检查该列是否存在的测试。有些人可能没有运行过之前的迁移,因此不会有该列。