我对 Rails 相当陌生。请我需要一些帮助,我正在建设一个数字图书馆。
我很想在我的应用程序中添加软删除选项。
现在,我在表中添加了一个带有布尔数据类型的列删除,并且我还在控制器中为软删除定义了操作,但是我在定义模型中软删除操作的范围时遇到了问题,以便动作可以在控制器中调用。
我想要一个默认为 false 的软删除范围,然后当我删除一本书时,它在数据库中更新为 true。
控制器动作
def softdelete
@book.softdelete
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully deleted.' }
format.json { head :no_content }
end
end
软删除迁移
class AddDeleteToBooks < ActiveRecord::Migration[5.2]
def change
add_column :books, :delete, :boolean, :null => true
end
end
我剩下的就是如何在书籍模型中定义软删除的方法。
我将不胜感激任何形式的帮助。谢谢你。
您想要做的是创建一个 softdelete 方法,它更新删除字段(我认为您需要重命名它,因为它是 Rails 中的保留字)
class Book < ActiveRecord::Base
#add a model scope to fetch only non-deleted records
scope :not_deleted, -> { where(soft_deleted: false) }
scope :deleted, -> { where(soft_deleted: true) }
#create the soft delete method
def soft_delete
update(soft_deleted: true)
end
# make an undelete method
def undelete
update(soft_deleted: false)
end
end
并更新您的控制器以从现在开始仅获取未删除的记录
def index
@books = Book.not_deleted
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句