How do the relationships magically function when only the models are altered?
If I want a ‘has__and___belongs___to__many’ relationship, what should I name the table (so Rails can use it) that contains the two foreign keys?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Short answer: You can’t just tell the models that they’re related; there have to be columns in the database for it too.
When you set up related models, Rails assumes you’ve followed a convention which allows it to find the things you wrote. Here’s what happens:
You set up the tables.
Following conventions in Rails, you name the table in a particular, predictable way (a plural noun, e.g.
people). In this table, when you have a relationship to another table, you have to create that column and name it in another predictable way (e.g.bank_account_id, if you’re relating to thebank_accountstable).You write a model class inheriting from ActiveRecord::Base
class Person < ActiveRecord::BaseWhen you instantiate one of these models, the ActiveRecord::Base constructor looks at the name of the class, converts it to lowercase and pluralizes it. Here, by reading
Person, it yieldspeople, the name of the table we created earlier. Now ActiveRecord knows where to get all the information about a person, and it can read the SQL output to figure out what the columns are.You add relationships to the model:
has_many,belongs_toorhas_one.When you type something like,
has_many :bank_accounts, it assumes a few things:The name of the model that you relate to is BankAccount (from camel-casing
:bank_accounts).The name of the column in the
peopletable which refers to a bank account isbank_account_id(from singularizing:bank_accounts).Since the relationship is
has_many, ActiveRecord knows to give you methods likejohn.bank_accounts, using plural names for things.Putting all of that together, ActiveRecord knows how to make SQL queries that will give you a person’s bank accounts. It knows where to find everything, because you followed a naming convention that it understands when you created the table and its colums.
One of the neat things about Ruby is that you can run methods on a whole class, and those methods can add other methods to a class. That’s exactly what
has_manyand friends are doing.