ruby-on-railsformsformtastic

Rails: Showing Error Messages [bootstrap-sass, formtastic]


I'm using Bootstrap-Sass along with Formstatic. I thought an error message should be automatically shown next to the field with Formstatic like in this picture: here
(source: asciicasts.com)

But even if the user puts an invalid input, my app does not show an error message. This seems to be an easy problem but I cant figure out the reason behind.

PostController

# POST /posts
# POST /posts.json
  def create
@post = Post.new(params[:post])
@post.view = 0
@post.like = 0
@post.hate = 0

respond_to do |format| 
  if @post.save
    @posts = Post.paginate(:page => params[:page], order: 'like desc', per_page: 10) 
    format.html { redirect_to posts_path }
    format.json { render json: @post, status: :created, location: @post }
  else
    format.html { render action: "new" }
    format.json { render json: @post.errors, status: :unprocessable_entity }
  end
end

end

PostModel

  validates :name,  :presence => true
  validates :content, :presence => true,
                      :length => { :minimum => 10, :maximum => 300}

_form (Post)

<% @post = Post.new %>
<%= semantic_form_for @post do |f| %>
<%= f.semantic_errors :name %>
<%= f.inputs do %>
     <%= f.input :name, :label => 'name' %>
     <%= f.input :content, :label => 'body' %>
<% end %>
<%= f.actions do %>
    <%= f.action :submit, :button_html => { :class => "btn btn-primary" }, :as => :button  %>
    <%= f.action :cancel, :as => :link %>
<% end %>

UPDATE: In PostController, I deleted the following two lines

    #format.html { render action: "new" }
    #format.json { render json: @post.errors, status: :unprocessable_entity }

and added

    render @post.errors

Then, I got

@messages={:name=>["can't be blank"], :content=>["can't be blank", "is too short (minimum is 10 characters)"]}>

So the problem is that the way I'm rendering json is wrong. Could someone help me how to fix it?


Solution

  • You pass presence validation in name and content and length validation in content that means if you don't enter any value in name or content then it will give error like can't be blank and if content value length is less than 10 and greater then 300 then it will give error.

    If you want to pass validation for invalid input then you have to pass validates_format_of validation.

    You puts invalid input in name or content? Can you provide invalid input that you enter?

    Update

     # in /config/initializers/formtastic_config.rb. 
    
     Formtastic::SemanticFormBuilder.inline_errors = :sentence
    

    See Video : http://railscasts.com/episodes/185-formtastic-part-2

    Get Code : https://github.com/ryanb/railscasts-episodes/tree/master/episode-185