getdave
getdave

Reputation: 208

Rail Application Model/Controller & Routrs organisation

I'm trying to work on this Rails app which has the following objectives:

/foods/ - render a list of food categories (eg: Breads, Dairy, Biscuits...etc)
/foods/breads/ - render all Foods that are within the food category "Breads"
foods/breads/bagel - render a detailed view of the properties of the Food (in this example a Bagel).

Currently I have two models with associated controllers:

Foods - contains a list of foods (eg: bagel, rice, toast, rich tea biscuit...etc) and is set up to belongs_to a single Food Cat

Food Categories - a list of categories such as "Dairy", "Breads"...etc & is set up to has_many :foods

I'm really stuck on how to achieve my objectives. I really need advice on routing, controller actions and views.

Any suggestions?

Upvotes: 3

Views: 117

Answers (2)

Pan Thomakos
Pan Thomakos

Reputation: 34350

In your routes.rb file, I would do the following:

match 'foods' => 'FoodCategories#index'
match 'foods/:category' => 'Foods#index'
match 'foods/:category/:name' => 'Foods#show'

I would then create a scope for Foods by category:

class Food
  scope :by_category, lambda{ |category| joins(:categories).where('categories.name = ?', category) }
end

I would then have 2 actions in your FoodsController:

class FoodsController
  def index
    @foods = Food.by_category(params[:category])
  end

  def show
    @foods = Food.by_category(params[:category]).where('foods.name = ?', params[:name])
  end
end

And a single action in your FoodCategoriesController:

class FoodCategories
  def index
    @categories = Category.where(name: params[:category])
  end
end

That should leave you with having to implement 3 views: categories/index, foods/index and foods/show.

Upvotes: 1

Vlad Gurovich
Vlad Gurovich

Reputation: 8473

You should have a FoodsController and a FoodCategoriesController dealing with Food and FoodCategory models. if you follow the RESTful approache, then the routes neccessary to achieve the url configuration you listed will be as follows:

match '/foods' => 'food_categories#index'
match '/foods/:category_id' => 'food_categories#show'
match '/foods/:category_id/:food_id' => 'foods#show'

Your FoodCategoriesController will have methods index method which lists all the categories by performing FoodCategory.find :all lookup, as well as show method which will lookup a FoodCategory based on provided :category_id and display all the foods associated with it via has_many relationship. Your FoodController will have a show method that will at least take the :food_id and look up the Food instance associated with it. :category_id is not really neccessary here, but its a nice routing sugar.

Upvotes: 0

Related Questions