How do you allow users make custom shopping lists?

I asked Ryan bates, the owner of if he knew of any
documentation that would explain what code to use to allow users make
their own lists in RoR. He referred me to here. I’m trying to make it
so user A can make a shopping list and populate it with items like
eggs, fruit, oatmeal, etc. I know that I could easily make one
shopping list for all users to use but my situation is different. I
want user A to be able to make a list for different types of food and
such. The problem is, I don’t know if this is possible or how to do it
without other users seeing their shopping list. I’m very adamant on
letting users make their own shopping lists so any info on how to do
that is very much appreciated.

I’d start by creating various models to represent the user, the lists,
the items in the lists, and a pairing relationship between them (aka
a “join table”, or in Rails lingo, a “has many through”
relationship). For example, you could have 4 models:

Foodable (the join model)

User has all the standard fields you need for a user with
authentication, etc. To handle authentication, do a Google search for
“authlogic” and do some reading on it.

ShoppingList consists only of:


(You could also add “notes” or something to that effect here too, if
you wanted.)

Finally, Food would simply be:


…that’s it. So now you have:







Foodable (the join model between foods and shopping lists)


So you can see how, using foreign keys, we can link any number of
foods to multiple shopping lists without duplicating information in
the database. For example, if we had a food called “T-Bone Steak”, it
only needs to be listed in the database ONCE. Not hundreds of times.
Then, in the Foodable join table, we link its unique ID in the food
table (say that ID is 199) to every list in which it appears.

By linking the shopping list model directly to the user model (so
shopping_list belongs_to :user), we ensure that any single shopping
list belongs to ONLY one user at any given time, meaning that your
database select query (or a “find” on that model) will only return the
lists that specific user owns, never anyone else’s, making it all but
impossible that user A would see user B’s list.

This is basically a data architecture/database normalization problem.
I suggest looking up the basics of how ActiveRecord works, especially
model relationships such as belongs_to and has_many with the :through
option (you could also do a has_and_belongs_to_many, but I hear that
practice is falling out of favor these days because the
has_many :through allows you to work directly with the join model and
does the same thing.)

You were on the right track checking out Railscasts - Ryan does a
great job of breaking down complex topics to make them easy to
understand. I suggest you look through it a bit more to learn more
about how ActiveRecord works. In addition, check out Rails Guides:

Good luck.