2

I have a very basic rails app. I am playing around with validation.

Controller

class PagesController < ApplicationController
  def new
    @user = User.new
  end
  def edit
    @user = User.new(:state => params[:state], :country => params[:country])
    @user.save
  end
end

Model

class User < ActiveRecord::Base
    validates_presence_of :country
    validates_presence_of :state
end

Views/pages/edit.html.erb

<% form_for :user, @user, :url => { :action => "edit" } do |f| %>
  <%= f.text_field :country %>
  <%= f.text_field :state %>
  <%= submit_tag 'Create' %>
<% end %>

All I want to do is click Create when I have not entered anything and then have a validation come up and list the required fields. I've read some tutorials and they make it so simple. Why can't I get this to work? what am i doing wrong? When i create a scaffold then it works ok but that generates a scaffold.css in public/stylesheets. W/out scaffold right now i have no stylesheet in the public folder.

2 Answers 2

2

you're sending the form to the "edit" action, which doesn't do any processing. You need it to go to the "create" action, which should look something like this:

def create
  @user = User.new(params[:user])

  if @user.save
    flash[:notice] = 'Your user was successfully created.'
    redirect_to users_path
  else
    render :action => 'edit'
  end
end

Your form_for line can be short and sweet. Also, you need to call error_messages to get the auto-generated list of errors:

<% form_for @user do |f| %>
  <%= f.error_messages %>
  ...other fields go here...
<% end %>
Sign up to request clarification or add additional context in comments.

3 Comments

It's important for the OP to understand that new & create work together to create an new resource (new presents the form, create saves it to the database), and edit & update work together in the same way for existing resources.
in your answer...form_for @user needs to be form_for :user
Actually, form_for @user works fine for me - that's how all of my forms are setup. Odd...
0

See Rails conditional validation: if: doesn't working

It seems like you think validates ... if: works differently as it actually does. This line

validates :to_id, presence: true, if: :from_different_to?

translates to validate that the to_id is present if the from_different_to method returns true. When from_different_to evaluates to false then do not validate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.