- has_one,
- belongs_to,
- has_many,
- has_and_belongs_to_many
- polyphormic
- one-to-one
- one-to-many
- many-to-many
ActiveRecord supports the above mentioned relations and in fact, comes with set of key words which are easy to use, understand and pretty clean.
Let me take few snapshots from David's book:
Note:
- invoices is the table name
- orders is the table name
Now I am into order model, orders having invoices. so the key word that we use here is has_one and then followed by the model name (Note: It is not table name, this is not plural).
has_one :invoice
Next will go to invoice model, since invoices belongs to orders we use the key word belongs_to and then followed by the model name.
belongs_to :order
Well there is not xml written for models, no xml written for relationships. But simple convention and defined keywords done the job for us.
And as you might have guessed the has_many comes into use when the orders table is having relationship with one more table (say, line_items). The below snapshot will help you to understand the syntax and it's usage.
Will look into other keywords and other relationship in the following posts...
1 comment:
Hi,
Can you help me solving this problem... and it is
User has many Projects, Project has many users, and user has multiple roles for a Project.
Eg:
Ram, John are multi skilled persons.
Ram and John are associated with many Projects in a company
Project A has many Users (Ram, Shyam, John, Ryan)
In Project A, Ram takes the roles as 'Configuration Manager and Network Manager' and John takes the roles as 'Developer and System Administer'.
In Project B, Ram takes roles of 'Developer and System Administer' and Ryan takes roles as 'Configuration Manager and Network Manager'.
In Project C, all users are developers.
So we have three tables User, Project and Role
Users are Ram, Shyam, John and Ryan
Projects are Project A, Project B and Project C
Roles are Developer, System Administrator, Configuration manager and Network Manager.
How do we design this?
Thanks,
Uday.
Post a Comment