1

I have a CourseCategory model and a Course Model along with corresponding controllers course_categories and courses. A course belongs to a category and a category has many courses.

I want to have a page that shows courses in a particular category. Which controller does this function belong in? Should I nest these resources? Just looking for the best way to model this.

4 Answers 4

2

CourseCategories. Think of your URLs, thats the easiest way to make a decision like this:

example.com/course_categories/1

--or, better, use slugs for categories instead of ids and you'd get--

example.com/course_categories/awesome_courses/

However, it might be worthwhile to consider simple having a "categories" model rather than a "course_categories" model. Then you could nest categories under courses, and you'd get something like:

example.com/courses/categories/1 or example.com/courses/categories/hard

Sign up to request clarification or add additional context in comments.

Comments

0

I would say you are going to be displaying a coursecategory listing - therefore would belong in the coursecategory controller.

Comments

0

You can add this so the courses controller and take a parameter saying which category to respond with.

Or, if it makes sense, you can make courses a nested attributed of course_categories. Then this will be the default behavior.

EDIT Since I gave the opposite answer of someone else. The first suggestion would let you

/courses?course_category=math

or

/courses/math

Then look for the course_category in the controller

The second idea would let you do

/math/courses

Comments

0

An alternative would be to do something like

routes.rb

resources :course_catgeories do
   resources :courses
end

courses_controller.rb

def index
   @course_category = CourseCategory.find(params[:course_category_id])
   @courses = @course_category.courses
end

The logic here being, if you're listing courses for a category, then the conventional action for that is the index action. Except in this case, you're scoping the listing to a particular category. So if you think about it in those terms, I think this approach better models your domain.

This approach effectively produces the following routes:

/course_categories/ (category index page)
/course_categories/1 (category show page)
/course_categories/1/courses (course index page)
/course_categories/1/courses/1 (course show page)

Comments

Your Answer

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.