Is it an ok practice to define a resource in your routes file multiple times? 3+ times?

48 views
Skip to first unread message

Chris P.

unread,
Jun 9, 2014, 3:00:28 PM6/9/14
to rubyonra...@googlegroups.com
Noobie here. Let's say you have a Post, Comment, and User models. So
Post has_many comments, and User has_many comments.

If it good practice to do the following...

resources :posts do
resources :comments
end

resources :users do
resources :comments
end

etc?

I have a model in my schema that I believe I will likely have 3
different route resources for.

Or is better to just have the one, such as our first snippet of code
above, and then have a param that modifies what is returned, in this
example, passing in the user_id to just see comments for that user?

--
Posted via http://www.ruby-forum.com/.

mike2r

unread,
Jun 10, 2014, 8:54:20 AM6/10/14
to rubyonra...@googlegroups.com
IMO, it can be done either way.  If you use routes, it would be a little cleaner when you are using the same resource more than once to make a concern:

concern :commentable do
   resources :comments
end

resources :posts, concerns: [:commentable]
resources :users, concerns: [:commentable]

Chris P.

unread,
Jun 10, 2014, 1:56:34 PM6/10/14
to rubyonra...@googlegroups.com
mike2r wrote in post #1149390:
> IMO, it can be done either way. If you use routes, it would be a little
> cleaner when you are using the same resource more than once to make a
> concern:
>
> concern :commentable do
> resources :comments
> end
>
> resources :posts, concerns: [:commentable]
> resources :users, concerns: [:commentable]

When doing this, does this mean both of these resources would access the
same controller? How can I have them access different controllers, and
what would a proper naming convention be for each controller in your
example?

mike2r

unread,
Jun 11, 2014, 9:39:26 AM6/11/14
to rubyonra...@googlegroups.com
If you're referring to the comments resource, yes, both would post to the same controller in your format as well as the one I suggested.  If you want them to point to different controllers, you will need to go back to your original format and specify a controller, such as:

resources posts do
   resources comments, controller: "postcomment"
end


Chris P.

unread,
Jun 11, 2014, 11:05:13 AM6/11/14
to rubyonra...@googlegroups.com
Thanks!
Reply all
Reply to author
Forward
0 new messages