views:

258

answers:

2

I am working on an an application that allows a user to search for a particular book on Amazon using a given search criterion (e.g. title, keyword, author.) I am currently attempting to store these search results to a MySQL database, but am struggling with the concept of relationships.

It seems natural that I would structure the models something like this:

class Search < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :search
end

If a user makes a second search, however, I need a way to update the search results with the new books. My first inclination is to do something like the following:

Search.update(1,:books)

Does the update method work like this? Am I on the right track?

Also, I feel unsure as to whether updating search results in a database is even the right route to take. Could there potentially be negative effects if two users search at the same time? My only reasoning behind storing those search results to a database is that I need to display the information for the book they chose later in the user session. I would imagine that if I only updated the search results and there were multiple users using the tool that would overturn the entire purpose of using the database, as the second user's search results would overwrite the first user's search results. Is this true?

Could I, perhaps, store the information in the user's cookie?

A: 

Before thinking about how, you need to pin down your what. What is the required behaviour of your system?

Do you want one global search object shared by all users?

Do you want to store one Search object per user

Do you want each user to have a record of several searches?

Then adjust the search object accordingly, if your requirement is anything other than a single global search object then it either needs a realtionship with a User or "user id" attribute.

djna
A: 

Are you trying to keep track of all the searches a user has run, or just the last one? If it is the former you will need to keep track in the database, if the latter you can store the info in the user's cookie.

Shane Liebling