I'm using a hideous pattern in my code and I know there must be a better way to do this. Help me rethink what I'm doing.
My website is a kind of discussion forum. All replies to discussions are done on the DiscussionsController#show page, inline.
Some replies are invalid, though - for example, if you try and post a reply that has no text in it, it returns you to DiscussionsController#show with an error message.
Here's a brief outline of how I've implemented this workflow:
- User goes to DiscussionsController#show. This template has a reply form on it. There is no explicit RepliesController#new action.
- User submits reply form, which is POSTed to replies_path and handled in RepliesController#create.
- RepliesController#create is unable to save the reply because it's invalid (validates_length_of in Reply invalidates the object).
- RepliesController#create puts the reply object in session[:new_reply] and redirects to the discussion_path the user came from.
- DiscussionsController#show handles the session object...
Like so:
if session[:new_reply]
@new_reply = session[:new_reply]
session.delete(:new_reply)
end
And now show.html.erb has a newly-regenerated @new_reply object to inspect for errors.
There's something obviously wrong with this - you shouldn't store entire objects inside of the session. But since the Reply object we attempted to save in RepliesController#create is never saved, how do I persist it between controller action calls?
Or if there's a larger design solution, feel free to share it. This is so ugly it's hurting me. Thanks.