jeudi 21 janvier 2016

how is the scoping stack in RAILS 3.2 handled? I have a nice idea how to override a default scope, but really get stuck with active records logic.

Pre 0: I post 2 questions with almost the same intro here, but the requested/expected answers are very different

(other question is my solution ok?)

Pre: my question belongs to Rails 3.2 & plz. I don't want to discuss using default_scope at all; I know, that there are a lot of arguments not to use it (in wrong way)

I have the 'classical' soft delete records problem that is - as I think - almost perfectly solved with a default_scope, in my case the soft delete is for undo reasons. But I do not want to use unscope or plain sql if I need to access a deleted record

My Idea is just easy: since (where) scopes are just "and-ed", it does not make sense to have a default_scope where("deleted=false") and an other scope where("deleted in [true, false]")

What we get as SQL is something like

where  deleted=false and deleted in (true, false)  

so the next step is to look in previous "where" scopes before sending the last requested default_scope

if there is a "deleted=all" in where scopes, I send a "where 1=1" default_scope, if not, I send default a where "deleted = false" default_scope

But what ever I try, I can only see the where scopes in debugger, I can not find a way to look what scopes are already used from inside my Toast model.

So - imagine - I want to make a "puts" printing the scope chain for something like that:

Toast.not_to_dark.not_to_light.with_butter....

and Toast scopes

scope :not_to_dark
    where black < 80

scope :not_to_light 
    where black > 20

scope :with_butter
    where butter=true

It should be possible to collect that information when the "with_butter" scope is executed, but what ever I try, I fail, it feels like RAILS does not want me to get access to that information.

where is it how to get it?

Aucun commentaire:

Enregistrer un commentaire