jesper
jesper

Reputation: 227

Show the error instead of ruby default?

When using this I am getting the default design for Ruby on Rails enter image description here. How can i just print it as regular text in my current design like <%= error.text %>?

Model:

class Users < ActiveRecord::Base
  validates_presence_of :username, :message => "Du skal udfylde brugernavn"
  attr_accessible :email, :password, :username
end

Controller:

class HomeController < ApplicationController
  def index

     if params[:username]
         l = Users.new(:username => params[:username], :password => params[:password], :email => params[:email]).save!

         if Users.save? 
                z = Users.where(:username => params[:username]).limit(1).last
                @debugging="Yay"
         else
                @debugging = user.errors.full_messages.join("<br/>")
         end             
     end
   end
 end

Upvotes: 0

Views: 73

Answers (3)

Rahul Tapali
Rahul Tapali

Reputation: 10137

In model:

validates_presence_of :username, :message => "Du skal udfylde brugernavn"

In controller:

if user.save
   flash[:success] = 'User saved successfully'
else
   flash[:error] = user.errors.full_messages.join('<br />')
end

Edit

Not if Users.save? it should be l.save. (I suggest you to use User as model)

if params[:username]
   l = Users.new(:username => params[:username], :password => params[:password], :email => params[:email])

   if l.save 
      z = Users.where(:username => params[:username]).limit(1).last
      @debugging="Yay"
   else
      @debugging = l.errors.full_messages.join("<br/>")
   end
end

Upvotes: 0

Ivar
Ivar

Reputation: 5712

from Rails Guide to Validations:

To verify whether or not a particular attribute of an object is valid, you can use errors[:attribute]. It returns an array of all the errors for :attribute. If there are no errors on the specified attribute, an empty array is returned.

So, just display the errors hash..

Upvotes: 1

almathie
almathie

Reputation: 731

your_object.errors returns an associative array : {:username => "Du skal udfylde brugernavn"}

So you can do something like :

<%= user.errors[:username] %>

See more info on how to use this your views here (official Ruby on Rails doc) : http://guides.rubyonrails.org/active_record_validations_callbacks.html#working-with-validation-errors

Upvotes: 1

Related Questions