Screencast: Validieren mit Rails 3

Rails 3 bietet viel Neues bzgl. Validierungen. Ryan zeigt diese Woche wie die Neuerungen benutzt und komplexe Validierungen aufgeräumt werden können.

 

Download:

Download (14.4 MB, 9:53)
Alternativer Download für iPod & Apple TV (14.3 MB, 9:53)

 

Resourcen:

 

Quellcode:

gem install rails --pre
gem cleanup
rails store
cd store
rails g scaffold user name:string email:string
rake db:migrate
<!-- users/_form.html.erb -->
<%= form_for(@user) do |f| %>
  <%= render "shared/error_messages", :target => @user %>

  <div class="field">
    <%= f.label :name %><%= mark_required(@user, :name) %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><%= mark_required(@user, :email) %><br />
    <%= f.text_field :email %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

<!-- shared/_error_messages.html.erb -->
<% if target.errors.any? %>
<div id="errorExplanation">
  <h2><%= pluralize(target.errors.count, "error") %> prohibited this record from being saved:</h2>
  <ul>
  <% target.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
</div>
<% end %>
# application_helper.rb
def mark_required(object, attribute)
  "*" if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator
end

# models/user.rb
validates :email, :presence => true, :uniqueness => true, :email_format => true

# lib/email_format_validator.rb
class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || "is not formatted properly")
    end
  end
end

Eingestellt am 26.04.2010 um 16:42

Kategorie: Tutorials

Be Sociable, Share!

Kommentare für diesen Artikel wurden geschlossen.

Suchen auf rubyonrails.de

Aktuelle Rails Version + Abhängigkeiten:

Gem rails-3.0.0
actionmailer (= 3.0.0, runtime)
actionpack (= 3.0.0, runtime)
activerecord (= 3.0.0, runtime)
activeresource (= 3.0.0, runtime)
activesupport (= 3.0.0, runtime)
bundler (~> 1.0.0, runtime)
railties (= 3.0.0, runtime)

Rails auf Rubyforge
Rails auf Github