如何获得一个模型来指定pre-必要条件? [英] How to get a model to specify a pre-requisite condition?

查看:217
本文介绍了如何获得一个模型来指定pre-必要条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型Post.rb,我想有只返回的帖子如果将已删除列是0。换句话说,当用户删除帖子,它不会从数据库中删除的项目,但而轮番删除以1所以,如果我跑Post.find(:所有),我希望它自动添加条件中删除='0'。我如何去从我的模型这样做呢?

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?

谢谢!

推荐答案

default_scope 将是最简单的方法可以让你继续使用的东西像 Post.find(:所有)不用担心删除的条目,但你可能要问自己,为什么你周围保留删除的记录呢。你能简单地删除它们失去任何有价值的东西?如果是的话,有可能比软删除更好的答案。 软麻烦删除,例如,认为非常沉重反对这种做法,并提供避免他们一些建议。

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.

我个人对 default_scope 不算什么,但它的可以的会导致混乱,在这我已经用它几次,我已经总是要么回去,并删除它,或者把难看的 with_exclusive_scope helper方法在我的模型周围明确地得到。

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.

所以,虽然不容易,因为 Post.find(:所有),我会推荐使用 named_scope 而不是

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

,然后用 Post.active.find(:所有) Post.active.find(PARAMS [:ID])。我觉得它更清晰地传达了code的意图,那么它可以让你重新定义什么是积极的,是在未来,如果你的业务逻辑的改变,它不会让你通过 with_exclusive_scope跳篮球,如果你真的想要检索 Post.find(:所有)。(在管理应用,例如)

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. :)

编辑2 :您可能想看看 acts_as_paranoid 宝石,看起来来管理很多东西你(同时仍然允许您访问已删除的记录,而无需使用 with_exclusive_scope )。

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).

这篇关于如何获得一个模型来指定pre-必要条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆