0

I read "Multitenancy with Rails" by Ryan Bigg and I'm creating a multi-tenant application using Ruby on Rails.

I make two models, Tenant and User. Tenant has many User, User belongs to Tenant.

To associate these models, I made this file,

active_record_extensions.rb

ActiveRecord::Base.class_eval do
  def self.scoped_to_tenant
    belongs_to :tenant
    association_name = self.to_s.downcase.pluralize
    Tenant.has_many association_name.to_sym, class_name: self.to_s
  end
end

and add "scoped_to_tenant" to User.rb

class User < ActiveRecord::Base
  scoped_to_tenant
end

When I want to get all users of one Tenant(id=1), I can get it by these code.

Tenant.find(1).users

The question is, what is the difference between I write

belongs_to :tenant

to User.rb and use scoped_to_tenant method ?

In both case, Tenant.rb is this.

Tenant.rb < ActiveRecord::Base
   has_many :users
end

Thank you for answer. I may get English wrong, so please tell me if you can't understand something.

1
  • Maybe, these are same things and the reason to create scoped_to_tenant is just for using as a helper...?
    – okeigo
    Feb 18, 2015 at 9:23

1 Answer 1

0

A call to scoped_to_tenant method call the method belongs_to for you and add the many association to Tenant.

This is same as doing this :

# app/model/user.rb
class User < ActiveRecord::Base
  belongs_to :tenant
end

# app/model/tenant.rb
class Tenant < ActiveRecord::Base
  has_many :users
end

The benefit of the scoped_to_tenant is that you don't care about adding has_many relationship to Tenant model. If you only have one model to associate with Tenant, you don't need this extension.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.