Thursday, February 25, 2010

validates_confirmation_of

0 comments

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

0 comments

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

0 comments
Validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application’s terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and this ‘acceptance’ does not need to be recorded anywhere in your database (if you don’t have a field for it, the helper will just create a virtual attribute). 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

0 comments
Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Need for validations
  • 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.
Validation Story

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_each

haml.tutorial for Rails developers

0 comments
How to Convert Let’s start off with some basic ERB that we want to convert. ERB <strong><%= item.title %></strong> Haml %strong= item.title In Haml, we write a tag by using the percent sign and then the name of the tag. This works for %strong, %div, %body, %html; any tag you want. Then, after the name of the tag is =, which tells Haml to evaluate Ruby code to the right and then print out the return value as the contents of the tag. Unlike the ERB above, Haml will automatically detect newlines in the return value and format the tag properly. Simple tags are all well and good, but what about adding attributes to tags? HTML <strong class="code" id="message">Hello, World!</strong> Haml %strong{:class => "code", :id => "message"} Hello, World! The attributes are just a standard Ruby hash. The class attribute is “code”, the id attribute is “message”. Notice that in this example, we didn’t use =, so “Hello, World!” is interpreted as a normal string, not Ruby code. There is a simpler way to define this tag in Haml, since class and id are such common attributes and since most designers (and coders) are familiar with CSS, we can use similar notation to describe this tag. Haml %strong.code#message Hello, World! Not only that, but since div tags are so common, you can leave off the tag definition and have it default to %div. Haml .content Hello, World! HTML <div class='content'>Hello, World!</div> Now what about something a little more complicated? ERB <div class='item' id='item<%= item.id %>'> <%= item.body %> </div> Pretty basic. This might be part of a partial or something. Let’s convert it to Haml. Haml .item{:id => "item#{item.id}"}= item.body This stuff is fun! Now, nesting is taken care of in Haml via whitespace. ERB <div id='content'> <div class='left column'> <h2>Welcome to our site!</h2> <p><%= print_information %></p> </div> <div class="right column"> <%= render :partial => "sidebar" %> </div> </div> Haml #content .left.column %h2 Welcome to our site! %p= print_information .right.column = render :partial => "sidebar"

.html.erb v/s .html.haml

0 comments

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.bio

ERB

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

0 comments

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
end

Here 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
end
The @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

0 comments
Rails relies on the MVC pattern. Model-View-Controller has some benefits over traditional concepts:
  • Isolation of business logic from the user interface
  • Ease of keeping code DRY
  • Making it clear where different types of code belong for easier maintenance
  • 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

Tuesday, February 16, 2010

Start With Ruby

0 comments
This blog is for the beginners who are truly madly and deeply in love with ruby on rails.firstofall let me introduce myself.I am mux99 a software programmer seeking a good career path in ruby on rails platform.It was on this Valentines Day (Feb 14-2010 that i just fall in love with ruby.
 

Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com