Simplify code on method about 4 models

I'm trying to get more into the Ruby mindset. I know I should accomplish
more with less code. I came up with this method that does work, but I
think could really use some simplification.

There is 4 models.
Company (belongs to Account)
  (belongs to Company)
  (belongs to Role)
  (to get the account id, I would need to do

User.role_id (if it's a 1, it means it's the Account Owner)
There is only ONE account owner per account.

So, when a "customer"(role_id=4) signs in, under the Users tab, he's
supposed to see two companies:
1) the company he belongs to
2) and the account owners company

So I need to come up with something like this:
@companies = Company.all(:conditions => ["id == ? or id == ?",
current_user.company_id, account_owner_company_id])

1) Coming up with the company he belongs to it's easy:

2) Coming up with the account owner company id it's more difficult and
requires several queries. The method I have does the following:
a) Finds the customer's account_id
b) Looks for ALL account owners in the database
c) Tries to match the customer's account_id to one of the account
owners id's
d) Finally, returns the account owner's company id


You can easily see that if the database grows, looking for ALL account
owners in the database can take up a lot of resources. Can you suggest
an easier way to find the account owner company id when being logged in
as a customer?

Your data structure feels a little weird to me - Presumably accounts
have multiple companies. So does someone with role_id == 1 own all the
companies in the account that the company_id points to? It feels a
little lopsided to have this one privileged company. I think
personally I would give account an owner_id attribute.

Anyway, assuming that users will grow rapidly but that an account will
only ever have a manageable number of companies in it, something like

all_companies_in_account =
owner = User.find_by_role_id_and_company_id(1,

would find you the owner.


Thanks Fred!

The reason of this setup (might need some adjusting) is that an Account
has an attribute paying_method. So only the account_owner is the one
that pays.

The account owner can add, edit or delete Companies and Users. He's the
administrator for that Account.

The Users under the account owner's Company, are kinda like managers or

The Users under other than the account owner's company are customers.

I think you can dispense with Company altogether and just have an
association class describing a User's relationship to an Account:

  has_many :users, :through => :memberships

  belongs_to :account

  belongs_to :user
  belongs_to :account
  has_one :role # agent, owner, etc.

~ jf

Sorry, typo. Should be:

  has_many :users, :through => :memberships

  has_many :accounts, :through => :memberships

  belongs_to :user
  belongs_to :account
  has_one :role # agent, owner, etc.