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.
Account
Company (belongs to Account)
User
  (belongs to Company)
  (belongs to Role)
  (to get the account id, I would need to do user.company.account_id)
Role

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:
current_user.company_id

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

---------------------------------------------------------------
def account_owner_company_id
  customer_account_id = current_user.company.account_id
  account_owners = User.find_all_by_role_id(1)
  account_owners.each do |ao|
    if ao.company.account_id == customer_account_id
      @this_one = ao.company_id
    end
  end
  @this_one
end
---------------------------------------------------------------

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?

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to