Pavel K. Pavel K. - 3 years ago 71
SQL Question

auto-filtering all activerecord queries in rails app

on our Rails 3 website we need to filter information dependant on which product customer has access to.

we could do it by adding

["product_id in (?)",[allowed_products_array]]

in each query executed anywhere in the app for each class which has product_id, but that would be a lot of changes and thus a lot of code to support, so i was thinking about automating this process somehow

what could be the best solution for such auto-filter?

i was thinking about adding global ActiveRecord query override for all classes connected to product but i am not sure how to accomplish that

Answer Source

use default_scope for this

in your case like

default_scope where("product_id in (?)",[allowed_products_array])

you can extract it into module and include into every model you'd like to have this functionality.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download