How to get a model to specify a pre-requisite condition?

…衆ロ難τιáo~ 提交于 2019-12-13 20:23:39

问题


In my model "Post.rb", I'm trying to have it only return posts if column deleted is 0. In other words, when the user deletes posts, it doesn't remove the item from the database, but rather turns deleted to 1. So if I run Post.find(:all), I want it to automatically add the condition "deleted = '0'". How do I go about doing this from my model?

Thanks!


回答1:


Yes, default_scope is going to be simplest method and will allow you to continue using things like Post.find(:all) without worrying about deleted entries, but you might want to ask yourself why you're keeping deleted records around anyway. Would you lose anything of value by simply deleting them? If so, there might be a better answer than a "soft-delete". The trouble with soft deletes, for example, argues very heavily against the practice, and provides a few suggestions for avoiding them.

I personally have nothing against default_scope, but it can get messy, and in the few times that I have used it, I've always had to either go back and remove it, or put in ugly with_exclusive_scope helper methods in my model to explicitly get around it.

So, while not as easy as Post.find(:all), I would recommend using a named_scope instead

class Post < ActiveRecord::Base
  named_scope :active, :conditions => {:deleted => 0}
end

and then using Post.active.find(:all) or Post.active.find(params[:id]). I think it conveys the intention of the code more clearly, it then lets you redefine what "active" is in the future if your business logic changes, and it doesn't make you jump through with_exclusive_scope hoops if you really do want to retrieve Post.find(:all) (in an admin app, for instance).

Edit: As I suspected, it looks like you're already looking for ways to get around it. :)

Edit 2: You might want to look at the acts_as_paranoid gem, which looks to manage a lot of this stuff for you (while still giving you access to deleted records without using with_exclusive_scope).




回答2:


The simplest way is probably to add a default scope to your Post.rb model:

default_scope :conditions => {:deleted => 0}



回答3:


In your model, you'll want to specify a default_scope. When you want to actually fetch these deleted posts, you'll have to override the default scope.

class Post < ActiveRecord:Base default_scope :conditions => {:deleted => 0'} end



来源:https://stackoverflow.com/questions/2073197/how-to-get-a-model-to-specify-a-pre-requisite-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!