Advancing with Rails, day 1
Posted on March 31, 2008
Filed Under Rails, Ruby, Web | Leave a Comment
Just finished my first day 'Advancing with Rails' courtesy of David A. Black. I'm happy to say that it's one of the most enlightening programming experiences I've had for quite some time.
It's rare that you get an opportunity to pick the brains of a real expert like David and with 3 more days of Ruby/Rails I'm sure there's plenty more good stuff to come.
Topics covered today included overriding ActiveRecord defaults (good for working with legacy databases, of which we have no shortage of here!), how to use initializers properly and why you might like to slim down your environment.rb. Composite primary keys (*blergh*), why class variables are tricky and best avoided, singleton methods and more!
Top two things for the day:
set_inheritance_column :fakecolumn
This is really useful when you have a 'type' column in your table and don't want Rails to think that you are working with single table inheritance. This is something that has caused me problems more than once.
Object.build(params[:associated])
By this I mean, say you had an auction model and
Auction has_many :items.
Should you want to create an auction and some associated items at the same time you might be tempted to do something like this in the controller:
@auction = Auction.new(params[:auction])
@item = Item.new(params[:item])
@auction.items << @item
This won't work because the @auction object hasn't been saved yet, doesn't have an ID and therefore doing:
@auction.items < @item
will fail as the auction_id column in @item won't be set.One way around this would be to put in the following before we create the new item:
@auction.save
This would work as @auction is now an ActiveRecord object. However, this has always seemed really scrappy. Today I learned that there is a much nicer way!
@auction = Auction.new(params[:auction])
@auction.build_item(params[:item])
@auction.save
In these three lines we've created the new Auction object and added an associated auction item by 'building' it. Nice eh?
Recently
- Slicehost
- History Meme
- Advancing with Rails, day 3
- Advancing with Rails, day 2
- Advancing with Rails, day 1
