2
votes

Hi I have nested resource:

resources :posts do
  resources :msgs
end

and some validations:

class Msg < ActiveRecord::Base
  belongs_to :post
  validates :body ,presence:true
end

a controller:

# msgs_controller.erb
def create
 @post = Post.find(params[:post_id])
 @[email protected](msg_params)
 @msg.user=current_user
 @msg.email=current_user.email
 @msg.autor=current_user.name

 if @msg.save
   flash[:notice] = t '.create'
 end
 respond_with(@post,@msg)
end

and a view: EDIIT: /views/posts/show.html.rb # /views/show.html.erb

<h2>Add a comment:</h2>
<%= form_for([@post, @post.msgs.build]) do |f| %>

    <% if @msg.errors.any? %>
        <div id="error_explanation">

          <h2><%= pluralize(@msg.errors.count, "error") %> prohibited this msg from being saved:</h2>

          <ul>
            <% @msg.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
    <% end %>


    <p>
      <%= f.label :body %><br />
      <%= f.text_area :body %>
    </p>
    <p>
      <%= f.submit %>
    </p>
<% end %>

the app doesn't shows the errors messages when body field is blank, but the validations are ok becouse the server show me ROLLBACK instead COMMIT. The problem is to show the error messages in the views, can you help me?

2
Is there anything at all in @msg.errors? What does the data in @msg actually look like at the point when you're trying to save? You mention that it is doing a ROLLBACK, but if the validation is really failing it would not try to do an INSERT at all. See edgeguides.rubyonrails.org/… - section 1.2, second paragraph. This indicates that maybe validations are not actually failing and something else is going wrong with the save (causing the ROLLBACK).Scott S
Does your Posts model have accepts_nested_attributes_for :msg? If so, I'm wondering if the errors would show up in @post.errors instead. Maybe give that a try.lurker
i have try to eliminate the validation in the msg model and the blanck comment is committed in the db. With the validation active the blanck comment is not committed but is rollbacked. I have seen this in server's log and throught database query.user1066183

2 Answers

1
votes

Check out this article on how to do flash messages the Rails 4 way: http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013

From the article:

# app/controllers/application_controller.rb
class ApplicationController
    ...
  add_flash_types :error, :another_custom_type
end

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    ...
    redirect_to home_path,
      error: "An error message for the user"
  end
end

# app/views/home/index
<%= error %>
0
votes

The form should be in the new and not in the show view. Then, you can render the page if not saved to display the error.

....
 if @msg.save
   flash[:notice] = t '.create'
 else
   render 'new'
 end
....