Making the weight CRUD work per user

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 =[: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 =
@weight = user![: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, 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, 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:


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:




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s