Martyn Bedford wrote:
So if I have my object I create a table called object(s) and create a
primary key called id, so good so far, now what I need to do is create
joins and foriegn keys to other tables, I have seen this working in a
few examples but I am lost as to the naming conventions for this.
This is pretty easy —
There are two basic ways to relate in ruby has_many or has_one and
belongs_to. As always, there are options to handle complex cases.
Check the api docs for these functions and much will become clear.
Basically the difference is where the foreign key lives. In belongs_to,
it is in the table for the model.
If you have a cities table and your object belongs_to a :city, you will
have a city_id field in the objects table. Note the plural/singluar -
the table is plural but the foreign key is singluar.
If you have a has_many or has_one relationship then the foreign key
lives in the other table. So to take the example further, in the City
model definition, you would put “has_many :objects” – no futher work
needed. Now the following should be true for any city with at least one
object: city.objects.city == city.