Sonal S.
Sonal S.

Reputation: 1442

error_messages in rails are not being displayed

In my users controller I have new and create action..

def new
 @user = User.new
end
def create
  @user.save!
end

and my new.html.haml is..

 - form_for @user do |f|
  = f.error_messages
  = label_tag "User Name"
  = f.text_field :user_name
  %br
  = submit_tag 'Add', :disable_with => "Creating…"

User.rb(Model)

validates_uniqueness_of  :config_name

But if I click on submit button with value already taken in text field it doesn't display error msg. But throws an exception.

 ActiveRecord::RecordInvalid in UsersController#create

    Validation failed: has already been taken

Please any one tell me why is it not displyaing error messages.

Upvotes: 0

Views: 91

Answers (2)

jvnill
jvnill

Reputation: 29599

You are using #save! which raises an exception when validations fail. You should use #save or still use #save! but wrap it inside a rescue block.

def create
  if @user.save
    redirect_to @user, notice: 'Created!'
  else
    render :new
  end

Upvotes: 2

shweta
shweta

Reputation: 8169

see save!

def create
  unless @user.save
     render :action => :new
  end
end

Upvotes: 0

Related Questions