开发者

Why is my rails simple validation not working

开发者 https://www.devze.com 2022-12-17 22:02 出处:网络
I have a very basic rails app. I am playing around with validation. Controller class PagesController < ApplicationController

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.


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 %>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消