I have got a form which is generated by model object.
<%= form_for(@pages) do |f| %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<% end %>
Here is the controller method for this:
def new
@pages = Page.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @post }
end
end
Here is the model code:
class Page < ActiveRecord::Base
validates :title, :presence => true
end
Now, how can I validate the form on submission.(i know that submit button is not there, i will add it later). I have used <%= f.error_messages %> in the form but it is giving me error :
NoMethodError in Pages#new
Showing C:/rorapp/app/views/pages/_form.html.erb where line #2 raised:
undefined method `error_messages' for #<ActionView::Helpers::FormBuilder:0x49b9ca8>
Extracted source (around line #2):
1: <%= form_for(@pages) do |f| %>
2: <%= f.error_messages %>
3: <p>
4: <%= f.label :title %><br />
5: <%= f.text_field :title %>
Trace of template inclusion: app/views/pages/new.html.erb
Rails.root: C:/rorapp
Application Trace | Framework Trace | Full Trace
app/views/pages/_form.html.erb:2:in `block in _app_views_pages__form_html_erb__975660997_39217440'
app/views/pages/_form.html.erb:1:in `_app_views_pages__form_html_erb__975660997_39217440'
app/views/pages/new.html.erb:2:in `_app_views_pages_new_html_erb___256256638_47476836'
app/controllers/pages_controller.rb:11:in `new'
Request
Parameters:
{"title"=>"",
"author"=>"",
"email"=>"",
"body"=>"",
"reference"=>"Google"}
Show session dump
Show env dump
Response
Headers:
None
How can I validate it?
If I’m understanding your question correctly, you want to know how to validate the form on submission and how to display errors when there are some?
The validations you have in your model currently will validate the field “title” when you hit the submit button. So I think you’re already good in that respect since that seems to be your only one.
To get errors to show up in your views, you want to use something like this is your form:
This handles any errors in an elegant way. If there is more than one error, the
pluralizemethod handles the pluralization of the word error so the sentence reads something like “2 errors have prohibited this from being saved.” That way, should you decide to add more fields, you’re already good to go.Then
pages.errors.full_messagesdisplays each error in a sentence that is understandable to a user.