Episode 16 - Refactoring searches

Vlcsnap-2010-04-27-13h50m28s57

Click on image above for a preview

Released: Apr 27, 2010, Running time: 64 min

In this episode:

We refactor the association between Brand and Search so we don’t run the search for duplicate search terms.

Tags: rspec, model, controller

Add to cart$5.00
  • Share

We refactor the association between Brand and Search so we don’t run the search for duplicate search terms.

In the current form, the associations between Brand and Search are:

  • Brand.has_many :searches
  • Search.belongs_to :brand

This allows for duplicate search terms to exist within the database, if they are associated with different brands. This is not desired because we end up running a search for each search term, making unnecessary queries against external services. Also, we end up having repeating search results inserted into the database, because each search result is associated with the search term.

Solution:

  1. Transform the has_many/belongs_to association between Brand and Search into a has_and_belongs_to_many association.
  2. Do not add duplicates: when adding a new search term to a brand, look for an existing term first and use it if found; create a new one if not.
  3. Clean up after ourselves: when removing a term from a brand, check to see if any other brands are linked to the search and, if not used anymore, destroy it.

Because these are not changes that will be noticed by the user, we don’t have to update any of the features. Their role at this point is just to keep us in check, to make sure we have not broken any of the functionality.

Screenshots

  • Vlcsnap-2010-04-27-12h44m37s233
  • Vlcsnap-2010-04-27-12h44m43s37
  • Vlcsnap-2010-04-27-12h44m59s195
  • Vlcsnap-2010-04-27-12h45m21s154
  • Vlcsnap-2010-04-27-12h46m06s98
  • Vlcsnap-2010-04-27-12h46m18s218
  • Vlcsnap-2010-04-27-12h47m48s88

No comments yet

Commenting is disabled.