class NamesValidator # Checks that first_name and last_name are within certain length def self.valid_length?(name) name.first_name.length < 20 and name.last_name.length < 10 end # Checks that first_name and last_name have the first character capitalized # capitalize turns HELLO into Hello; hello into Hello; etc def self.valid_case?(name) name.first_name == name.first_name.capitalize and name.last_name == name.last_name.capitalize end def self.non_conforming_method # This method will not be called during validation end end class Name < Validatable attr_accessor :first_name, :last_name # create getters and setters for instance variable name def initialize(first_name, last_name) @first_name, @last_name = first_name, last_name end end
Sunday, September 12, 2010
Thursday, February 25, 2010
validates_confirmation_of
Labels: validation helpers, Validations in Ruby on rails
You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with “_confirmation” appended.
class Person < class="symbol"> :email
end
In your view template you could use something like
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
This check is performed only if email_confirmation is not nil. To require confirmation, make sure to add a presence check for the confirmation attribute
class Person < class="symbol"> :email
validates_presence_of :email_confirmation
end
The default error message for validates_confirmation_of is “doesn’t match confirmation”.
validates_associated
Labels: validation helpers, Validations in Ruby on rails
You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, valid? will be called upon each one of the associated objects.
class Library <> has_many :books validates_associated :books end
This validation will work with all of the association types.
Don’t use validates_associated on both ends of your associations, they would call each other in an infinite loop.
The default error message for validates_associated is “is invalid”. Note that each associated object will contain its own errors collection; errors do not bubble up to the calling model.
validates_acceptance_of
Labels: validation helpers, Validations in Ruby on rails
class Person < ActiveRecord::Base
validates_acceptance_of :terms_of_service
end
The default error message for validates_acceptance_of is “must be accepted”.
validates_acceptance_of can receive an :accept option, which determines the value that will be considered acceptance. It defaults to “1”, but you can change this.class Person < ActiveRecord::Base
validates_acceptance_of :terms_of_service, :accept => 'yes'
end
Wednesday, February 24, 2010
Validations in Ruby on rails
- Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things can be difficult to implement otherwise.
- Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user’s browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
- Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it’s a good idea to keep your controllers skinny, as it will make your application a pleasure to work with in the long run.
- Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well.
The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.
- decrement!
- decrement_counter
- increment!
- increment_counter
- toggle!
- update_all
- update_attribute
- update_counters
Validation Helpers
Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object’s errors collection, and this message is associated with the field being validated.
Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
All of them accept the :on and :message options, which define when the validation should be run and what message should be added to the errors collection if it fails, respectively. The :on option takes one of the values :save (the default), :create or :update. There is a default error message for each one of the validation helpers. These messages are used when the :message option isn’t specified. Let’s take a look at each one of the available helpers.
1.validates_confirmation_of 2.validates_exclusion_of 3.validates_format_of 4.validates_length_of 5.validates_numericality_of 6.validates_uniqueness_of 7.validates_eachhaml.tutorial for Rails developers
Labels: Extras on rails, haml.tutorial for Rails developers
.html.erb v/s .html.haml
Labels: .html.erb v/s .html.haml, Extras on rails, Ruby On Rails
What is it?
Haml takes your gross, ugly templates and replaces them with veritable Haiku. Haml is the next step in generating views in your Rails application. Haml is a refreshing take that is meant to free us from the shitty templating languages we have gotten used to. Haml is based on one primary principle. Markup should be beautiful. However, its not beauty for beauty’s sake. Unspace Interactive and several other professional Rails shops use Haml exclusively for every one of their projects. In fact, it was created for use in highly productive environments. The beauty makes you faster. Haml is a real solution to a real problem. Stop using the slow, repetitive, and annoying templates that you don’t even know how much you hate yet. Try something new — make templates fun and beautiful again! If you sit down and try using Haml, you will learn it within 20 minutes.Haml
#profile .left.column #date= print_date #address= current_user.address .right.column #email= current_user.email #bio= current_user.bioERB
<div id="profile"> <div class="left column"> <div id="date"><%= print_date %></div> <div id="address"><%= current_user.address %></div> </div> <div class="right column"> <div id="email"><%= current_user.email %></div> <div id="bio"><%= current_user.bio %></div> </div> </div>Tuesday, February 23, 2010
How do I make a form that handles multiple models?
Labels: How do I make a form that handles multiple models?
This question is asked quite frequently. Scaffolding and simple Rails tutorials show you how to create one model per form. Unfortunately, sometimes this is not sufficient.
In this article we will make one form that creates two models: Project and Task (where a project has many tasks). What I would like to do is have the first task be created the same time the project is created (in the same form). Here's the new action in the controller:
# in the projects_controller.rb def new @project = Project.new @task = Task.new endHere we are creating the models which will contain the default values - we can set any default values in this action and they will be reflected in the form.
Next we make the form containing fields for these two models. Of course you could add as many fields as you need to for each model:
# in the projects/new.rhtml New Project<%= error_messages_for :project %> <%= error_messages_for :task %>
<%= start_form_tag :action => 'create' %> Project Name: <%= text_field :project, :name %>
First Task: <%= text_field :task, :name %>
<%= submit_tag 'Create' %>
<%= end_form_tag %>
Pretty simple. Now comes the tricky part, the create action. First the code, then I'll explain it.
def create @project = Project.new(params[:project]) @task = @project.tasks.build(params[:task]) if @project.save redirect_to :action => 'index' else render :action => 'new' end endThe @project instance variable is set normally, but what's up with how the task is created? We use a fancy method to help us out here. The @project.tasks.build method creates a task (just like Task.new) and adds it to the @project at the same time. Pretty cool huh?
Next we call @project.save. This method is actually doing a lot. First it checks if the project and all of its tasks are valid. If something is invalid it returns false, otherwise it saves both project and task and returns true. This save method is very convenient and handles everything for us automatically.
Why do we bother setting the @task instance variable you may wonder? We need it in case the validation fails and we render the 'new' form again.
The creation of the project along with the task is finished, but how about editing? Normally, with this kind of set up, I use separate forms for editing. In this case I would list the tasks on the project 'show' page with an edit link next to each one.
Monday, February 22, 2010
The MVC Architecture
- Isolation of business logic from the user interface
- Ease of keeping code DRY
Models
A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.
Views
Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that performs tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
Controllers
Controllers provide the “glue” between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
MVC can be well understood by a figure given below Note 1.The solid line represents a direct association 2.The dashed an indirect association