Nick B
Nick B

Reputation: 1101

How to set up partially nested resourceful routes?

On my Rails site, users post Listings of items they want to sell. Other users can browse these listings and click a link to contact the seller, which should create a MessageThread:

# MessageThread properties...
listing_id
poster_id # (listing_id's owner.. this is a shortcut for to avoid joins on the database)
sender_id
body # (text of message)

MessageThreads are never created outside the context of a Listing, so I nested their resourceful routes. However, they don't need the Listing context to be viewed/edited after they are created.. it's only necessary for the new and create actions. I set it up like this:

resources :message_threads, :only => [:show, :destroy]

resources :listings do
   resources :message_threads, :only => [:new, :create]
end

I can't seem to figure out the form_for syntax in the new action view for the MessageThreadsController... I do form_for @message_thread but that isn't working. Is this the right way to set this object up? Should I avoid using resourceful routes, or maybe pass the listing ID as a parameter in the URL, instead of nesting the routes? Or always reference the message_thread underneath a listing?

Upvotes: 0

Views: 164

Answers (1)

drhenner
drhenner

Reputation: 2230

This should work:

form_for @message_thread, :url => listing_message_threads_path(@listing)

You can always run this in the command line

rake routes | grep message_thread

The new link would be

new_listing_message_threads_path(@listing)

Upvotes: 1

Related Questions