This seems like a lot of statements for a controller method - remember the principle of "skinny controller". How about you refactor this into a method in a helper module? And we can go from there.