In the previous two posts I created a full CRUD, using scaffolding, for weights and a way to get the current user. The weight CRUD, as it was, allowed you to edit data for any user (check out the screenshots). Moving from there to editing data only for yourself was trivial.

In the views I just removed the user_id field, no big deal. In the controller it gets interesting, there you have lines like the following:

@weights = Weight.all
@weight = Weight.find(params[:id])
@weight = Weight.new
@weight = Weight.new(params[:weight])

Those four lines get all the weights, find a specific weight, create a new weight object and create a new weight object with the goal of saving it to the database with the data from the web form; respectively. Of course those lines are not all together, but all over the controller.

I replaced those lines with the following:

@weights = user.weights.all
@weight = user.weight.find(params[:id])
@weight = user.weight.new
@weight = user!.weight.new(params[:weight])

And that’s it! Line 1 gets all the weight for the given user. If user is a not-in-the-database user, then that’s an empty list. The same for line 2. Line 3 could still be Weight.new, because that object is only used for displaying the form, but I like being consistent. Line 4 gets interesting. Shortly after line 4 I do a @weight.save, so the user must exists on the database to save the weight, that’s why I user user!

The whole patch can be seen in the screenshot:

sano-009

That program is GitX in case you are wondering. A MacOSX GUI for Git, which I really love.

I tried it by opening two browsers (Firefox and Safari) and putting some data in. I left the user id in the listing just to be sure:

sano-010

sano-011


Leave a Reply

You may also like:

Hi, I'm Pablo, this is my web site. You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 4,048 other subscribers

I'm writing a book

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I've been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Keep on Posting Kubuntu Lisp Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek startups technology Ubuntu web WordPress

I've been writing for a while:

%d bloggers like this: