我对rails相当陌生。请给我一些帮助,我正在建设一个数字图书馆。
我希望将软删除选项添加到我的应用程序中。
现在,我在表中添加了带有布尔数据类型的列 delete ,并且在控制器中为软删除定义了操作,但在模型中定义软删除操作的作用域时遇到了问题,以便在控制器中调用该操作。
我想要一个默认为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我留下的是如何在图书模型中定义软删除的方法。
任何形式的帮助我都会感激的。谢谢。
发布于 2019-05-20 13:31:04
您想要做的是创建一个软删除方法,更新delete字段(我认为您需要重命名它,因为它是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
endhttps://stackoverflow.com/questions/56221497
复制相似问题