开发者

Ruby On Rails Model/Controller Question

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开发者_Python百科 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.


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


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


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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜