Rails: best practice to scope queries based on subdomain?

后端 未结 5 1482
傲寒
傲寒 2020-12-24 04:17

I\'m working on a Rails (currently 2.3.4) app that makes use of subdomains to isolate independent account sites. To be clear, what I mean is foo.mysite.com should show the f

5条回答
  •  北海茫月
    2020-12-24 04:31

    Have you tried defining the default_scope a lambda? The lambda bit that defines the options get evaluated every time the scope is used.

    class Page < ActiveRecord::Base
      default_scope lambda do 
       {:conditions => "organization_id = #{Thread.current[:organization]}"}
      end
      # yadda yadda
    end
    

    It's essentially doing your third option, by working in tandem with your before filter magic. But it's a little more aggressive than that, kicking in on every single find used on the Page model.

    If you want this behaviour for all models you could add the default_scope to ActiveRecord::Base, but you mention a few being a couple of joins away. So if you go this route, you'll have to override the default scopes in those models to address the joins.

提交回复
热议问题