Test Your Knowledge
Quiz
Where do you specify data relationships?
How much effort does Rails put into enforcing relationships between models?
What does the
collectmethod do?How can you check to see whether a related record exists?
Why would you want to go to the trouble of creating a nested resource?
When would you use a
before_filter?What does
form_fordo when it is passed an array for its first argument?What two columns are needed in a join table?
Why would you want to index the columns of a join table?
Where do you tell Rails about new methods you’ve added to the scaffolding?
Answers
Relationships are specified in models. The models on both sides of any given relationship must identify how they relate to the other model. For example, a
has_manyrelationship in one model should be matched by abelongs_torelationship in another model.Rails doesn’t put any effort into enforcing relationships between models. If you have constraints to impose, you need to create code that checks and enforces them.
The
collectmethod iterates over a collection and gathers the results from a block. It’s an easy way to turn a list of data into aselectlist, for instance.You could check for a related record with
find, but in most validation contexts it’s easier to use thevalidates_existence_ofplug-in. (If you want to check for a related valid record, then Rails’ built-invalidates_associatedwill work.)Nested resources have some programming aesthetic appeal, but they’re also useful for making relationships ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access