Don’t forget to look at The Rails Way blog.
Move logic into your model. This lets you break functionality into more granular components and makes testing easier. Keep your controllers skinny. Jamis blogged about this principle here.
Use before filters to setup state before your controller runs. Use before_create in your models.
ActiveSupport helps you make your code intention revealing. Ruby code can be self documenting.
has_many, belong_to makes your code powerful easy to use, but many users don’t use the power of the associations.
Document.find_all_by_user_id(@john.id) vs @john.documents # this one hits the db once and then stores the objects in memory. After the call you don't have to keep hitting the db. </pre>
You can do the same with@john.documents.find(:all, :conditions => .... </pre>
try this:@cool.documents.find_by_user_id(@john.id) </pre>
then define it as a method:@cool.documents_authored_by(@john.id) </pre>
just be sure to not duplicate the method in both the tags and authors models that is difficult to maintain. You might prefer:@john.documents.tagged_with(@cool) </pre>
Don't use the '!!' idiom. What you are doing is saying not not.def account_code? !!@account_code.nil? # will return false if account_code nil end </pre>
this is betterdef account_code? @account_code ? true : false end </pre>
or you can do this# make sure to document true because... false because... def account_code? if @account_code true else false end end </pre>
I'm tired of typing code. I'll post a link to the slides when they get them up. Simplify 'New' for creating objects with associations by creating a method in your model called build with associations that does that work for you instead of creating a bunch of objects and then associating them in the controller Simplify your routes. If you are pointing to the same controller all the time use with_options you can make better urls like thisdef to_param "#{id}-#{name}" end find(params[:id]) </pre>
but you have to be careful in your controller to make sure that other methods work with params[:id]returning new do |billable| billable.contract = Contract.new end </pre>
is the same asbillable = new billable.contract = Contract.new return billable </pre>
but looks cool How do you deal with validations when you have a lot of associations. I have dealt with this and it sucks. I have had to force the various objects to validate and then pull the errors into an error object then show the errors from that object.