Ruby on Rails one to many database relationships

Using : Ruby 1.9.2, Rails 3.1.3

Please note : I’m new to all this Ruby on Rails stuff, I’m posting these articles so if I make mistakes hopefully people will point them out.

As a developer on top of the Microsoft ASP.NET and SQL Server stack you have a lot of good tools at your disposal, but a lot of these tools abstract developers away from what is really happening under the covers. Whether that is a good or bad thing I’ll leave for another post.

Creating a one to many relationship in a .NET application is as simple as:
1, Creating the database tables including necessary foreign keys
2, Add the tables and map the relationship using Linq 2 SQL or Entity Framework

…and away you go.

Ruby on Rails is quite a bit different as their is no visual designer for modeling the relationships. It is done through adding attributes to model classes. Here’s a simple walk through on how to create a simple one to many relationship where a Category can have many Products belonging to it.

First lets create a new rails app called store, in a terminal window type:

rails new store

Change into the store directory, and lets use scaffold to create our category and product application components:

rails g scaffold category name:string
rails g scaffold product name:string description:text category_id:integer

Notice that we add the foreign key field of category_id to this command.
Open up the directory in textmate and edit the model files for category and product. In category.rb add:


and in product.rb add


Now back in your terminal window run rake db:migrate to create your product and category tables, and run rails s to start the application.

Open a browser and navigate to http://localhost:3000/categories and add a couple of categories such as cars and books.
Now if you navigate to http://localhost:3000/products you will notice that if you try to create a new product you will have to know the exact category_id the product should belong to. What would work better is if you had a nice drop down menu to select the category. Lets do this!

Open up the products_controller.rb and find the new method below the @product = add the following line:

@categories = Category.all

Also find the edit method in the products_controller, and add the same line.

This will give us the category data to populate our drop down selection list. We now need to change the form for creating a new product. In Views/Products open the file _form.html.erb and change the line:

<%= f.text_field :category_id %>


<%= collection_select(:product, :category_id, @categories, :id, :name, {:prompt => false })  %>

:product – the name of the object you are setting the value for, eg in our form the object is @product set in the form helper
:category_id – the name of the property to be set by the selection
@categories – the collection of objects to display in the drop down
:id – the value property for each object displayed
:name – the display property for each object displayed
{:prompt => false} – this is optional, and is set so no prompt (such as ‘Please select an item’) is displayed.

If you save all the files now and go to create a new product you’ll notice that you get a nice drop down list of categories to chose from. Hurrah!

The final thing you may want to improve is the index.html.erb and show.html.erb views within the Views/Products folder. At the moment these two views will display the category_id number rather than the actual name of the category. If you want to fix this simply change:

<%= product.category_id %>


<%= %>

in the index.html.erb and show.html.erb files.

Ruby on Rails and PostgreSQL

Using : Ruby 1.9.2, Rails 3.1.3

Please note : I’m new to all this Ruby on Rails stuff, I’m posting these articles so if I make mistakes hopefully people will point them out.

As I found out today while getting back into Ruby on Rails (for the third attempt) Heroku now uses PostgreSQL as it’s database data store. It therefore makes sense to use this database type as your local development db rather than sqlite3 so you don’t come across any issues later upon deployment.

As with all rails stuff these instructions will depend on the versions you are running with, so please take note of the date this article was published. This is also the reason I wanted to write up how I got it to work, as it seems a number of pages that show up in Google searches are a bit out of date.

1, First step is to install PostgreSQL. You can download and install it from here:

I installed it with all the defaults

2, Next install the PostgresSQL drivers for Ruby by using Ruby Gems. At a terminal prompt type

gem install pg

3, You can now go ahead and create a new rails application, but this time you want to add an extra argument to let rails know you want to use PostgreSQL:

rails new myApplication -d postgresql

4, Now you need to edit your database.yml file to let rails know how to connect to your PostgreSQL instance. This is stored in the config directory of your rails application. There will be 3 different database settings for development, test and production. Update each sections to include the username and password, here’s how the development connection will look like:

adapter: postgresql
encoding: unicode
database: myApplication_development
pool: 5
username: postgres
password: ******
5, Save database.yml and go back to your terminal prompt. Now lets generate a table, model, view and controller for some product objects:

rails g scaffold products name:string description:text stock_level:integer

6, Once this has run you can use the rake command to first create the databases and then run the migration scripts

rake db:create:all
rake db:migrate

7, If you open up your pgAdmin application which PostgreSQL should have installed in Launchpad you’ll be able to see your 3 new databases. If you expand myApplication_development through the Schemas and public nodes you will be able to see that 2 tables have been created. The products table and a table for keeping track of migrations.

8, The final test to see if it is all working is to type:

rails s

and browse to http://localhost:3000/products – and try using the application!

Installing Ruby on Rails 3.1 – My Tips

Please note : I am in no way an expert – I’m just learning Ruby and Ruby on Rails and hope people may point out my mistakes by reading these posts.

Ensure you have the latest version of XCode installed. This is a big download, but ensure you get it before trying to update Ruby or install Rails.

Install RVM (Ruby Version Manager)
Simply copy the install command into a terminal window at:
to install the latest version of RVM from Github

Once RVM is installed you’ll see a long message. Read through this and notice the line you need to add into your .bash_profile file. If you are new to mac os/unix like me then .bash_profile and .bash_rc files are a bit of a mystery so I used this link to edit mine:

Close your terminal window and open a new one. Type in:

rvm -list

to see the versions of ruby installed. If version 1.9.2 isn’t installed type in:

rvm install 1.9.2

Once it is installed, run rvm -list again just to see if there. To switch to the new version you simply type:

rvm 1.9.2

to make it the default next time you open a terminal window use:

rvm 1.9.2 –default

Now lets make sure we have the latest version of Ruby Gems. Ruby Gems is an easy way to download and manage packages – you can think of packages as .NET assemblies and libraries that you will want to use in your Ruby or Ruby on Rails apps. It is a good idea to make sure you are running the latest version of Ruby Gems by using the command:

gem update –system

Once that is done, lets install rails:

gem install rails

and then make sure we have Sqlite3 – which is a light weight database Ruby on Rails will use by default during development

gem install sqlite3

Now you should be able to get up and running with creating your first rails app!

A week in Scotland

Last week Sophie and I spent the week driving up to and around Scotland. We did this 8 years ago, traveling up to Loch Ness – and wanted to do it again. It’s a long drive up from Reading, but the scenery is great and if you share the driving it is not too bad. We decided not to book anywhere again and just to drive until we found somewhere nice or were tired. This is quite a fun way to explore somewhere and means you don’t have to be at certain places at certain times. You can also stay longer when you find somewhere nice!

This time we bought the Lonely Planet Guide to Scotland which made the journey more fun as you can read up on the places before deciding whether to stop.

Roman Camp Hotel

We wanted to stay in Killin, although all the accommodation listed in the guide book were full. We carried on up a bit further north and came across the Roman Camp Hotel at Callendar. Rooms were great and dinner was excellent. Also the gardens were pretty impressive.

B&B in Pitlochry

We didn’t fancy driving all the way up to Loch Ness from Callendar so chose somewhere else to stop on the way up. We stayed at the Home from Home B&B which was very nice and 5 minutes walk from the main high street. We arrived at Makays bar to use their free wifi, but ended up staying till late to partake in their free whisky tasting session.

Pitlochry is a great place with a few good pubs. Also they have an impressive Hydro Electric Dam you can walk across and if it is the right season see fish jump up the fish ladder.

Inch Hotel and Loch Ness

8 years ago when we visited in August we managed to pull up at the first B&B we liked the look of in Drumndrochit and stay there. The ‘no vacancy’ signs being displayed as we drove around however made us realise this time it wasn’t going to be so easy!

After driving around the Loch for a while we came into Fort Augustas and the first main hotel we came across luckily had one double room left for 2 nights – so we quickly snapped it up. The hotel is very nice, with great views of the Loch from the garden and also from our room. The food was also great.

There is plenty to see and do at Fort Augustas, from Loch Ness tours to watching the boats use the 5 or 6 locks to get out of Loch Ness and into the canal. We enjoyed eating and drinking at the Loch Inn, their fish n chips and sticky toffee pudding were especially nice!

Abbey Bridge B&B

On our journey back from Scotland 8 years ago we wanted to stop off somewhere on the way back to break the journey up. Diving off the M6 to take a view of Hadrians Wall we came across a nice looking pub with accommodation called Abbey Bridge (Pub, Inn or Hotel – not sure back in 2003). Upon calling to make a booking this time the place had been taken over and turned completely into a B&B. It’s still a great place to stay with really nice rooms, an honesty bar for drinks, yummy breakfasts and lots of things to see and do close by. Lanercost Priory is only 2 minutes down the road, and Hadrians Wall about 20 minutes walk away. Brampton is the closest small town and is a £5 taxi ride away. We ate at the Howard Arms ( which served really nice food and had a friendly atmosphere.

Overall a fantastic week, hopefully we won’t wait 8 years before going back to Scotland. Don’t be put off by the long drive, the scenery makes it all worthwhile.

Starting an email newsletter

This week saw the first SharePoint Weekly email newsletter go out. After listening to lots of success stories of email newsletters on Mixergy and speaking to Peter Cooper about the Ruby Weekly and Javascript Weekly email newsletters he has running I wanted to get something up and going for SharePoint. There is so much content written about SharePoint each week by Microsoft and bloggers it’s difficult to stay up with what’s important. Dan Usher was the holder of although he wasn’t doing anything with the domain name. Dan was nice enough to donate the url to the new project.

Last week I put up a couple of pages, a simple page allowing people to sign up and a sample page of SharePoint Weekly #1 which didn’t actually go out, but gave people a good taster.

Just mentioning the newsletter a couple of times on Twitter and asking people to re-tweet it has managed to grab 170 signups. From just a few tweets and no other marketing I think this is a good indication that people want a SharePoint newsletter.

What has worked really well is using the Click To Tweet service. When people signed up for the newsletter they were directed to a simple page that said ‘thank you’, but adding a link to Click To Tweet asking them to let their Twitter friends to know about SharePoint Weekly has helped people mention the newsletter on Twitter and go a little viral.

Next week I’m going to ask a few bloggers to mention the newsletter and hopefully get a new batch of subscribers. Putting together the newsletter should only take a couple of hours each week, and doing it helps me keep on top of what’s going on in the SharePoint world. The end game is tohopefully make a little side money from non-intrusive adverts in the emails, but we’ll see how that goes as the subscribed number increases.

How Come That Idiot’s Rich and I’m Not?

Also this week I quickly finished the book How Come That Idiot’s Rich and I’m Not? It was an impulse buy while shopping last weekend, which is unusual as I usually only get books recommended by others and after checking Amazon reviews.

The reviews and comments on Amazon for the book are a real mixed bag. I sped through the book which is a good sign, and although it doesn’t offer too many original ideas – it’s good to read them again. I’ve taken quite a few notes from the book and have put it on the read again shelf, so don’t be put off by the ratings and comments on Amazon. Never judge a book by its cover 🙂

Building a Facebook App – week 1

Building a Facebook App – week 1

With the newest release of the Facebook C# SDK I decided to revisit the Social Books idea I have been working on with a friend. Previously we had build the web app outside of Facebook – you could sign in with your Facebook credentials through Facebook Connect and we’d then grab the pages and items you liked in Facebook and try to make you some book recommendations.

I decided to try and build a much more simple version of the application that would allow you to post to your Facebook wall what current book you were reading, and also ask your friends for new book recommendations. I also wanted to build this as a Facebook Canvas Application rather than a standalone web site in the hope that more people would trust it and authenticate and allow their Facebook details to be passed in.

The Facebook C# SDK is a real joy to work with. It’s got some good sample applications and code snippets up on the site. With the existing code we already had using the Amazon web service to retrieve books I was able to put together something in 2 days and launch it.

You can try the application out here:
Social Books Facebook App

The hope is the app will be quite viral. By posting a short message to user’s Facebook wall when they select the book they are reading I hope their friends will be interested to click on the link and then sign up and post the book they currently have open.


I’ve been running some adverts on Facebook to try and attract some initial users. I was hoping the viral effect of people posting the books they were reading on their walls would mean that one advert enticed member would lead to 3 or 4 eventually coming over. Last week I spent £33.91 on Facebook ads which got 46 clicks.

Overall stats.

Here are the stats for Social Books from week 1.

Users : 59
Books Added : 50

This is pretty good for a first week, although I had hoped the viral aspect of posting messages to your Facebook wall would have meant a larger number. It’s a good start though and something to work on and try to increase as we move into week 2.
I need to build in some better tracking of users so we can tell where new registrations are coming from – adverts, wall postings, friend invites etc…

Unfortunately the process in Facebook for submitting your App to the App Directory is broken! Hopefully they’ll get this fixed soon as I’ve read getting your site submitted can lead to an influx of new users (at least for a short while)

Week 2 Plans

This week I plan one new development feature, and a different attempt on marketing.
The new feature will allow you to add books to your ‘Shelf’ that you’ve previously read. Upon doing this you’ll get the choice as to whether you want to post the book to your Facebook wall. If you are going through and adding 50 books in one go that you’ve read over the past 2 years you might not want to let your friends know about every one of them.

I’ve switched off the Facebook ads and will now try a little bit of Twitter marketing. Also on Thursday I’m planning to send out an email newsletter to all the registered users to try and keep return usage of the site up and let everybody know about the new features for them to try.

If you’ve any ideas on how to do extra marketing around Facebook Apps please leave them in the comments!

Introducing ToDo Rewards

I was looking at the post-it notes over my desk last week and started thinking about how I manage tasks, and also about the things that motivate me to get tasks done. Sometimes I’m really motivated and the day flies by with all tasks accomplished by the end of it, other days I get virtually nothing done and the day drags.

I think there’s a pattern emerging that the days that are most productive are also the days I’m most organised. My tasks are written down, and broken into steps if necessary – and I feel a sense of accomplishment as I strike them out. Wanting to create something new last week I thought about how a web app could make me more productive each day. It would need to help me do a few things…

1, be more organised
2, get motivated
3, feel accomplishment when tasks are done
4, feel accountable – encourage me to get my tasks done!

So I’ve built something simple called ToDo Rewards –

Yes it needs a design implement – but the functionality is there 🙂

The idea is that each ToDo item has a number of points against it. As you complete it, these points are added to your daily productivity total. From trying this out for a few days you certainly do get motivated to improve your daily points total. Lets see how ToDo Rewards achieves the 4 original aims set out above.

1, Being Organised
My ToDo items need to be in ToDo Rewards for me to be able to complete them and get the points value for doing them. Also you can setup re-occurring tasks that automatically get created for you each day in your ToDo list.

2, Get Motivated
Seeing the points total rising each day as you accomplish more is a good way to get motivated. Also I’ve created ToDo Rewards so you have a public profile – so others can see how productive you are each day (this also covers accountability). Here is my public ToDo Rewards page.

3, Feel Accomplishment
You get points, tasks have a strike through line, what more accomplishment do you need? You can also share your completed task lists on Twitter of Facebook to brag to your friends/co-workers.

4, Feel accountable
There is a public view of your ToDo list showing the tasks, which you’ve completed and your total points for that day. This is good for sharing with friends and colleagues to show what you’ve already got done, and what else needs to be done. Not everything needs to be shared of course – if you mark a task as private it won’t show in the public view.

So through some simple openness, game mechanics and accountability – ToDo Rewards can help make you more productive and have a little fun along the way.

There are many ideas around tasks that could be implemented…here are a few…
1, Rewards – get rewards throughout the day as you hit certain productivity point scores
2, Analysis – track through weeks and months how productive you’ve been and spot trends
3, Social – find people who have similar tasks to do, help them out or share the workload
4, Team management – allow managers to set tasks and priorities for team members

Please give it a try at , and let me know your feedback…

To Don’t List

Dan Pink wrote a great article in the Telegraph this week:

Why we all need a to don’t list

Here’s my to don’t list for 2011 – let’s see how I get on…

Don’t open Outlook before 11am
Don’t drink alcohol
Don’t eat chocolate
Don’t drink caffeine
Don’t eat red meat

Oddly enough the most difficult one is probably keeping Outlook closed until 11am!!!

This week I’m going to be reading Sir Ken Robinson’s book The Element. I saw his interview on Mixergy and so got the book when I spotted it in the shop this week.

Started working on a new project this week – non SharePoint this time. Looking forward to discussing in a few weeks.

Embrace the ‘Not invented here’ attitude

I found the new podcast by Scott Hanselman and Rob Coneroy on Saturday called ‘This Developers Life‘. I’ve listened to a few episodes and have really enjoyed them so will be subscribing to it through iTunes. The podcast I’m referring to in this blog post is titled Audacity where they kick the podcast off with speaking to John Resig the creator of jQuery. John was mentioning at the time of starting jQuery there were some other good Javascript frameworks around such as and Prototype, but he started jQuery because he just wanted to build his own tools to use.

This reminded me of the ‘Not invented here‘ attitude – which is usually frowned upon in the workplace. Companies or individuals do not want to use something because they haven’t built it, and they’d rather build there own. Rather than being looked upon as being a negative, I think people should embrace the ‘Not Invented Here’ attitude and go and build whatever they want – even if someone has done it already. If we all went with the same Javascript library John Resig would never have started jQuery. I feel embracing ‘Not Invented Here’ is key for innovation and changing things for the better! Now go out and start building…!

Block time wasters from your work day

I was feeling pretty burnt out on Thursday night so Brett suggested I take Friday off to make a long weekend. Three days away from my computer sounded like a great idea – so I willingly accepted his suggestion.

A number of weird things happened in a row. I saw Andrew Warner post on Twitter about a new eBook called ‘Get out of Jail Free Card‘. As I feel as though I’ve been drowning in email and todo lists I bought it and had a read. It’s short, to the point, and I’m going to implement quite a few things from it. I highly recommend it!

After reading the eBook I started thinking about the things I waste my time on during the day – email, Facebook, Twitter, BBC news/sport, Hacker News, Techmeme etc. I have a Windows laptop, Macbook Pro and iPad. I realized I need to limit all these time wasting activities (except email – need to just batch that) to my iPad! That leaves my 2 laptops as work devices for me to concentrate on being productive. I’ve edited the hosts file on my Win7 laptop now to block all these time wasters…

I wouldn’t ever claim to be as great a thinker as Seth Godin, but it was really weird how he posted a blog article suggesting exactly the same on the same day!

Are you making something

Looking forward to next week, I feel it’s going to be a productive one!