Ruby on Rails: Relationships, Nested Resources, and AJAX in Rails April 22nd, 2015

  • Most common relationship types for models
    • One-to-one
    • One-to-many (parent/child relationships)
      • The parent has many children
      • The children belong to a parent
    • Many-to-many
      • A book has many authors
      • An author has many books
  • Create model in the middle so info can be reused
    • A doctor has many patients through appointments
  • Use the resource generator to generate migration, model, resource route, controller (no actions are generated), helper, assets (JavaScript or CoffeeScript / SCSS), tests & fixtures, but not any views
    • Migration adds t.references :book, index: true which is a foreign key column translated into book_id
    • Project example…
      bin/rails g resource review name:string stars:integer comment:text book:references
      bin/rake db:migrate
  • Nested routes for resources accessed only in the context of a parent resource
  • Associations are business logic, calculations, aggregations, and destruction
    • On model … Book.minimum(:price)
    • On association … book.reviews.average(:stars)
  • Use helpers for view logic to keep views clean
  • When creating forms for nested routes, you must supply the parent and child objects in an array to the form_for method
  • Review::STARS.each do |star| … the Review model has a stars constant (STARS = 1..5) … constants should be all caps (except classes which are initial capped and camel-cased)
  • When destroying a parent you need to remember to destroy the children too
    • Use the dependent option on associations to destroy the associated objects
      • Typically used on has_many associations
      • destroy causes callbacks to run on child objects
      • Other common values: delete_all, restrict
    • has_many :reviews, dependent: :destroy
  • Extra queries impact performance! … Avoid “N + 1” selects
    • Use includes to eagerly fetch associations
  • reviews.map(&:stars) … is equivalent to… reviews.map { |r| r.stars }
  • Unobtrusive JavaScript … separation of functionality from presentation
  • Support for AJAX in Rails … remote form, link, and button helpers
    • Handle different formats with respond_to and/or respond_with
  • Turn off layouts for Ajax requests
    • layout ->(controller) {controller.request.xhr? ? false : ‘application’}
  • Rails security
  • Deployment resources
  • ActionMailer lets you send emails from your application