开发者

How to write a mark_as_deleted method in Ruby on Rails?

开发者 https://www.devze.com 2023-02-12 21:58 出处:网络
I\'d like to write a method which should work like the destroy method in any Rails default controller but shouldn’t really delete the data. Rather it should set a flag or something which I can evalua

I'd like to write a method which should work like the destroy method in any Rails default controller but shouldn’t really delete the data. Rather it should set a flag or something which I can evaluate in my views to not show this data any more.

So when the user clicks on ’Delete’ the corr开发者_运维百科esponding action should mark the data as deleted but not purge the data from my database.

What’s the most elegant way of writing such a method? I’m using Rails 3.


If all you want to do is show or hide data I would have a boolean is_visible field in the database.

Also, rather than evaluating in your view whether or not to show this data I'd put that logic in the model, in a default_scope (available in rails 3). So something like this (assuming you want to show/hide Articles)...

# model
class Article < ActiveRecord::Base
  default_scope where(:is_visible => true)
end

Obviously, your delete method should just set the is_visible boolean to false and on creation it should default to true.

Then you just need to be careful if your data has relations to other data. In this example, if you have Articles and they have Comments then maybe you don't want the Comments to show up anywhere if an Article is marked as not visible.


In some of my apps, I have added a column onto content types called status, which can be either "posted", "draft", or "removed". This way, users can make drafts or remove posted items without messing up the index views.

As far as elegance, it might not be the best, but I just create a new_draft method on the content types, which creates a new object with status set to "draft". Then, when the user posts their draft, I call a post method which sets status to "posted". Once posted, if a user removes their item, I call a remove method which (you guessed it!) sets status to "removed".

0

精彩评论

暂无评论...
验证码 换一张
取 消