How to validate user input in RoR?

ruby-on-rails, validation

Solution

First, don't add meaningless messages to validations, default error messages are good.

Second, change your code to something like this in controller:

def new
  @pool = Pool.new
end
def create
  @pool = Pool.new(params[:pool])
  if @pool.save
    flash[:notice] = "Some text indicating it was created"
    redirect_to pool_path(@pool)
  else
    flash[:error] = "Something is wrong while validating"
    render :new
  end
end

and view use form helper:

<% form_for @pool do |f| %>
  <%= f.error_messages %>
  <%= f.label :question, "Enter your question:" %><br>
  <%= f.text_field :question %><br>
  <%= submit_tag "Send" $>
<% end %>

This way you have validation in mode, and in controller you only need to check if model can be saved. It not, then in your view form can display error_messages for that model.

For displaying flash messages in layout place:

<% if flash[:notice] -%>
  <p class="notice"><%= flash[:notice] %></p>
<% end -%>
<% if flash[:error] -%>
  <p class="error"><%= flash[:error] %></p>
<% end -%>

Problem

I really don't know advice with validating user input. I'm begining with RoR. I read many pages about this issues, but I never get, what I want. Before RoR, I programmed in Java. My problem is: How I can do validate empty field and show error messages? Here are code fragments: polls_controller.rb ``` class PollsController < ApplicationController def create @poll = Polls.new @poll.question = params[:question] @poll.author_ip = request.remote_ip end def show end def new end def edit end end ``` polls.rb ``` class Polls < ActiveRecord::Base has_many :options validates_presence_of :question, :message => 'Something is wrong...' end ``` create.html.erb ``` <p> <% form_tag polls_path do %> <%= label_tag :question, "Enter your question:" %><br> <%=text_field_tag :question, params[:question] %> <%=submit_tag "Send" %> <% end %> </p> ```

Original source

Related problems