# Global Scope based on Subdomain

**URL:** <https://www.ruby-forum.com/t/global-scope-based-on-subdomain/169479>\
**Category:** Rails\
**Created:** [June 4, 2009, 9:47am UTC](https://www.ruby-forum.com/t/global-scope-based-on-subdomain/169479 "2009-06-04T09:47:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![KnightOfNi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/cab0a1/32.png) [@KnightOfNi](https://www.ruby-forum.com/u/KnightOfNi)\
**Post date:** [June 4, 2009, 9:47am UTC](https://www.ruby-forum.com/t/global-scope-based-on-subdomain/169479/1 "2009-06-04T09:47:43Z")

</div>

Hi, I’m a noob trying to figure out the best way to limit queries by a  
particular condition that is dependent on the subdomain of the site.

I have a table “places” with a field called “subdomain”. Say I have  
another table that belongs to places called “knights” (contains  
“place\_id”). Like so:

`places` table - Place.id, Place.subdomain  
`knights` table - Knight.id, Knight.place\_id

On the site, “heredia.knightsofni.es”, I only want to show the  
knights who live in Heredia wherever knights are shown.

My questions are these:

1. What is the best way to set the “active” place globally? Right now  
I am setting an instance variable @active\_place in  
application\_controller.rb like so: @active\_place = Place.find  
(:first, :conditions =\> [‘places = ?’, subdomain]). Is this OK, or is  
there a better way so that the @active\_place data is more globally  
available?

2. How can I constrain by place while staying RESTful? Right now I’m  
putting if/then statements in my controller methods like so: if  
@active\_place { @knights = Knight.by\_place } else { @knights =  
Knight.all }

Thanks for the help,  
Ni!

---

<div class="post-metadata">

**Author:** ![KnightOfNi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/cab0a1/32.png) [@KnightOfNi](https://www.ruby-forum.com/u/KnightOfNi)\
**Post date:** [June 5, 2009, 12:54am UTC](https://www.ruby-forum.com/t/global-scope-based-on-subdomain/169479/2 "2009-06-05T00:54:37Z")

</div>

Basically I need a default\_scope that constrains by kingdom. Is there  
some way to do something like this?:

class Knight \< ActiveRecord::Base  
belongs\_to :kingdom  
default\_scope :include =\> :kingdom, :conditions =\>  
[‘kingdoms.subdomain = ?’, current\_subdomain]  
…

But I see no way of getting the current subdomain inside the model.

Thanks (Ni!)
