Tuesday, June 10, 2008

Andrzej's Rails tips #11

Today I'm going to show you two tips, both related to Rails controllers.

Use the current_user object whenever you access its data

Instead of

@order = Order.find(params[:order_id])

do this:

@order = current_user.orders.find(params[:order_id])

Thanks to that, you don't have to check whether this order belongs to the user, you just need to handle ActiveRecord::RecordNotFound exception.

Move all the logic from your controller to the model

I know you already read this statement many times, but I will repeat it anyway.
In your actions you shouldn't manipulate your model objects, do it in the model class itself. Here's a simple example:

BAD CODE:

class OrdersController < ApplicationController
def update
@order = current_user.orders.find(params[:order_id])
if params[:order][:amount] > 0
@order.prepare_invoice
@order.send_email
@order.mark_as_paid
@order.notify_producers
end
end
end

BETTER CODE:

class OrdersController < ApplicationController
def update
@order = current_user.orders.find(params[:order_id])
@order.pay(params[:order][:amount])
end
end

class Order < ActiveRecord::Base
def pay(amount)
if amount > 0
prepare_invoice
send_email
mark_as_paid
notify_producers
end
end
end

No comments: