2
\$\begingroup\$

I'm doing a site at the moment (first Rails site, learning as I code) and I'm concerned that I'm over complicating the routes.

My associations boil down to:

class Recipe < ActiveRecord::Base
 has_and_belongs_to_many :categories
 belongs_to :book
end
class Category < ActiveRecord::Base
 belongs_to :category_type
 has_and_belongs_to_many :recipes 
end
class Book < ActiveRecord::Base
 has_many :recipes
end

I want to end up with URLs like this:

/books/3/recipes #to show all recipes from book 3
/category/12/recipes #to show all categories from category 12
/recipes/3 #to show recipe 3

The good news is I have this all working, but in the course of doing so I feel like I may have strayed a little from "the Rails way" and I was wondering if someone could take a look and let me know if I've gone wrong. The bits I'm particularly concerned about are my routes.rb file (because I appear to be repeating myself):

resources :books do
 resources :recipes
end
resources :categories do
 resources :recipes
end

In particular, the recipes#index action, which seems a little verbose:

def index
 if(params[:category_id])
 @recipes = Recipe.find_by_category(params[:category_id])
 elsif(params[:book_id])
 @recipes = Recipe.where(:book_id => params[:book_id])
 else
 @recipes = Recipe.find(:all)
 end
end

Now, it might be that this is all absolutely fine, but I just want to check before I get too much further in!

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 30, 2012 at 18:46
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

This is probably fine, though there are other ways to do it like passing filters to /recipes (?category_id=x or ?book_id=x). Your controller action is probably fine too, though I may have considered making multiple controllers.

Though i'm not sure why you're doing find_by_category instead of the a find_all_by_category or the same .where as you're doing for book_id. Also, Recipe.all is more rails 3.

answered Feb 1, 2012 at 5:59
\$\endgroup\$
1
  • \$\begingroup\$ Thank you, I eventually ended up refactoring all of this. I realized that I was trying to organize my routes around URLs which "sounded nice" without realizing that I was sacrificing quite a lot of nice-ness in the process (essentially by becoming obsessed with the "/recipes" bit at the end of the URL). You've given me something to check out though! \$\endgroup\$ Commented Feb 1, 2012 at 17:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.