Okay, so here is my question. I have a 3 different models, People, Roles, Client, and Store. Clients have many Stores and can also have many people. Stores have many people. People have various roles. 1 Person can work at multiple stores, and they may have different roles at each store.
For example. Joe may be an assistant manager at one store and a manager at another store. What I would like to be able to do is pull the correct roles by doing something like
Store.find(1).people.find(1).roles
(would return ‘assistant manager’ for example) or
Store.find(2).people.find(1).roles
(would return ‘manager’ for example). Is this possible to do in ActiveRecord?
I’ve created a table :roles_people which has the following definition:
create_table :roles_people, :id => false do |t|
t.references :role
t.references :person
t.references :store
t.references :client
end
However i can’t figure out how to get associations to work properly using this table. Can anyone point me in the right direction?
Thanks
Assume that all of those classes inherit from
ActiveRecord::Base😉You’re going to need to setup the migration and database structure to mirror these relationships. For each
belongs_tothere is an:object_idfield on the table reference the appropriate table’s id.Your query is going to need to look something like:
I would probably add a method to the store model to make this a little easier:
This way you can find the roles using:
Or, better yet:
Which changes our finder to:
I would say that this last method is the most ideal since it causes only a single query, while each of the other options execute two queries to the database per role look-up (one to find the store, and one to get the roles for a person_id). Of course if you already have the Store object instantiated then it’s not a big deal.
Hopefully this answer was sufficient 🙂