Tintin81
Tintin81

Reputation: 10207

Ruby on Rails: How to model Organisations and Clients?

I am building an application where a User can have many Clients (which cannot be shared among Users).

It is a fairly small application but it could happen that two Clients belong to the same Organisation. So it would be nice to have an extra table to hold all the information about the Organisation. It could also happen that a Client is a private Client and does not belong to any Organisation.

I know in database design this is fairly common, but how can this be modelled in Rails?

Upvotes: 0

Views: 371

Answers (3)

Jon Snow
Jon Snow

Reputation: 11892

User has many clients.
Client belongs to user.

This is fairly simple. The "clients" table would have a foreign key "user_id" if you're using a relational database.

Between clients and organizations, is it One-to-Many? or Many-to-Many? If it's one-to-many, you can do

Organization has many clients.
Client belongs to organization.

If it's many-to-many, you would need a mapping table

Organization has and belongs to many clients.
Client has and belongs to many organizations.

Learn more about associations in Rails ActiveRecord here

Upvotes: 0

rewritten
rewritten

Reputation: 16435

The answer is what have been stated by @peter-duijnstee, with the additional constraints asked:

class Organization < ActiveRecord::Base
  belongs_to :user
  validates :user, :presence => true
end

class Client < ActiveRecord::Base
  belongs_to :user
  belongs_to :organization

  # note the final "s", it validates a field
  validates :user, :presence => true 

  # no final "s", validate using a method
  validate :organization_user, :if => :organization_present?

  def organization_present?
    organization.present?
  end

  def organization_user
    errors.add(:organization_id, "is not allowed") unless organization.user_id == user_id
  end
end

Upvotes: 1

Peter Duijnstee
Peter Duijnstee

Reputation: 3779

How does an organization relate to the users? If users and organizations are independent from each other the simplest solution would be to have...

User         - has_many :clients
Organization - has_many :clients
Client       - belongs_to :user, belongs_to :organization

But I'm guessing there's more involved here? Are you looking for a many-to-many solution?

Upvotes: 1

Related Questions