3

Rails correctly handles a validation on a forum system, ensuring a post contains text. The issue is that if the validation fails, it redirects to 422 instead of back to the new action. The following is from the rails output:

Completed 422 Unprocessable Entity in 156ms (Views: 143.4ms)

Mongoid::Errors::Validations (
message:
  Validation of User failed.
summary:
  The following errors were found: Mongoid forums posts is invalid
resolution:
  Try persisting the document with valid data or remove the validations.):
  app/decorators/mongoid_forums/controllers/application_controller_decorator.rb:7:in `update_current_user_time'

I tried my best to debug it. Ultimately this is what it appears to do (according to the rails output):

  1. Go to create
  2. Fail at saving (because validation error)
  3. Redirect to the new page (the user never actually gets to see it, because the next step just takes over)
  4. Redirect to the 422 page, without the user ever seeing the new page with what they did wrong

Here is the code it gets up to: https://github.com/NJayDevelopment/mongoid_forums/blob/master/app/controllers/mongoid_forums/posts_controller.rb#L43

  @post = @topic.posts.build(post_params)
  @post.user = mongoid_forums_user

  if @post.save
    @topic.alert_subscribers(mongoid_forums_user.id)
    @topic.forum.increment_posts_count
    flash[:notice] = t("mongoid_forums.post.created")
    redirect_to @topic
  else
    flash.now.alert = t("mongoid_forums.post.not_created")
    render :action => "new"
  end

Is something particularly wrong with this method of creating a model and saving it? I tried some other solutions, like changing build to create or new and then setting the fields. It gets all the way to rendering new as far as I can see, but I don't get the form.

Ultimately all I want is that when a user tries making a post without text, they are redirected right back to new post form with a flash error.

njny
  • 559
  • 2
  • 15

0 Answers0