简体   繁体   中英

Nested routes for comments without using resources

I am in the process of building a forum and the threads are setup and viewing no problem. While in the process of trying to create the comments within a thread, I seem to be confused with how to setup the routes. Normally I know people have nested routes:

resources :threads do
  resources :comments
end

Though the difference is my routes do not use the resources method as I have them setup individually:

get '/thread' => 'threads#discussion'
post '/create_thread' => 'threads#create'
get '/create_thread' => 'threads#new', :as => :new_thread
get '/threads/:id' => 'threads#show', :as => :thread_show
get 'threads/edit/:id' => 'threads#edit', :as => :edit_thread
put '/threads/edit/:id' => 'threads#update', :as => :update_thread
delete 'threads/:id' => 'threads#destroy'

Thread/threads replaced the actual location name

Is there a way for me to place nested routes for the comments within each thread? I've give the proper associations for each model (Users, Threads, Comments) and added the user_id, thread_id to the Comments model.

If you have any knowledge on the correct way to setup the routes for the comments or know of an article, please list it here.

Thank you so much!

EDIT

The comments will be placed directly onto the thread page and not a new page.

Joe

You can do nested routes "manually" like so:

get '/threads/:thread_id/comments/new' => 'comments#new'
get '/threads/:thread_id/comments/:id' => 'comments#show'

And CommentsController's new action can do something like:

def new
  @thread = Thread.find(params[:thread_id])
  @comment = @thread.comments.build
end

However, I strongly agree with Jordan's advice above ; your routes are a bit messy, not fully RESTful, and would be much easier to express via resourceful routing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM