If you are dealing with a legacy database with weird names of tables and keys that don't follow rails practice for table naming than you will probably have a problem figuring out how to connect all the dots of your application. On top of that if you have to deal with "many-to-many" relation than you have a real tough task to accomplish. So let's go over one example how you can deal with this problem with ease.
A PROBLEM
Let's say you have a database table 'A(ID)', a table 'B(ID)' and a table 'AB(ID, ID_A, ID_B)'. 'A' has many of B's and 'B' has many of A's so 'AB' is a join table. You have to create models with the same names as database tables (in rails your database table name should be plural and your model should be singular so this is one more problem for you). And on top of that you need to create a scope in model 'A' to get data from table 'A' but you need to use some columns from table 'B'. For example (just to make you clear what we need to do) you have patients, physicians and appointments. And you have to find all physicians that have patients born in 1974. So in our example in table 'B' you would have one more column 'REQUIRED_YEAR'.
MODELS
Now that we defined our problem we can start developing our models:
As you can see, there are a lot of tricks in here, so be careful about every single line of code. Regardless of the rails naming conventions I always put 'class_name', 'foreign_key' and 'primary_key' options when I define a has_many or belongs_to associations. Maybe it's a few extra characters of code but I feel a lot safer not thinking what rails is doing 'under the hood' connecting names of the associations with model names.
A SCOPE
And finally let's create a scope in 'ModelA' to get all the data from table 'A' where a record from 'A' is connected to 'B' through 'AB' with a required year of 2012. Next image is a complete 'ModelA':
Now from console you can simply call:
Corresponding SQL query that is generated:
THE END
And that's it - pretty simple if you know the basics. I hope this can save you some time coding.