Test Your Knowledge

Quiz

  1. Where do you specify data relationships?

  2. How much effort does Rails put into enforcing relationships between models?

  3. What does the collect method do?

  4. How can you check to see whether a related record exists?

  5. Why would you want to go to the trouble of creating a nested resource?

  6. When would you use a before_filter?

  7. What does form_for do when it is passed an array for its first argument?

  8. What two columns are needed in a join table?

  9. Why would you want to index the columns of a join table?

  10. Where do you tell Rails about new methods you’ve added to the scaffolding?

Answers

  1. 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_many relationship in one model should be matched by a belongs_to relationship in another model.

  2. 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.

  3. The collect method iterates over a collection and gathers the results from a block. It’s an easy way to turn a list of data into a select list, for instance.

  4. You could check for a related record with find, but in most validation contexts it’s easier to use the validates_existence_of plug-in. (If you want to check for a related valid record, then Rails’ built-in validates_associated will work.)

  5. Nested resources have some programming aesthetic appeal, but they’re also useful for making relationships explicit and easily enforceable.

  6. before_filters are useful anytime you have code that should run in advance of all of the any other methods being called. It might be initialization code, or code that tests that certain conditions have been met.

  7. The form_for method uses the first argument to establish the target for the form’s results. If the first argument is a single object, it will create a URL pointing to that object. If the first argument is an array containing more than one object, it assumes that the first object contains the second, and generates a URL reflecting a nested resource relationship.

  8. A join table needs a column to store id values for each of the two models it connects. By Rails conventions, these columns are named model_id. A column linking to students, for example, should be student_id.

  9. Indexing both of the columns in a join table will give you much better response times than leaving them unindexed.

  10. You’ll need to add information about new methods in the routes.rb file, and create views for them as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset