At the Forge - Working with ActiveRecord
All of the constraints we have seen so far have been at the level of the database, rather than any application using that database. This potentially means trouble for the users of those applications who don't have access to the database definitions. After all, what is supposed to happen if the application tries to insert, delete or modify a row such that it violates a constraint?
The simple answer, and one that is still prevalent in a surprisingly large number of Web/database operations, is that the program simply reports an error. (Sometimes it even will indicate what the error was, needlessly exposing the offending SQL statement for everyone to see.) In some cases, the application indicates that there was a database problem, or something of the sort.
But, what we really would like is to avoid those sorts of database problems altogether. We would prefer to have the constraints in our database somehow be propagated to the application level, letting the application catch problems before they ever get to the database level.
Although ActiveRecord cannot do this, it comes very close, making it almost trivially simple for us to represent relationships between tables in a Rails application. Let's now create a simple Rails application that uses ActiveRecord to keep track of our address book and calendar information.
We begin by creating the skeleton Rails application by typing rails addressbook, which creates an addressbook directory and puts everything underneath that. Then, we modify config/database.yml to point to development, testing and production databases in the appropriate place. (See last month's At the Forge for an example of what database.yml should look like.)
Now, let's create basic models, controllers and views for the People and Appointment tables. We could use the script/generate program that comes with Rails to create them separately. But in many cases, it's easiest to create a bare-bones application, or scaffold:
ruby script/generate scaffold Person ruby script/generate scaffold Appointment
We can now start the test server on port 3000 (script/server); going to /People shows the current list of people and lets us create a new person. Click on the new person link, and you will see the page the scaffolding created. However, not all is perfect here—what happens if you click on the create button at the bottom of the page without entering anything in the text fields?
Assuming the definition of the People table described earlier, Rails will create a new person whose fields are all the empty string. We could solve the problem by modifying the definition of the People table, adding checks to ensure that the contents of each field is a non-empty string—but if we were to do this, Rails would show us the database error, complaining that we had violated an integrity constraint.
The solution is to modify the Person object so that it catches such errors, forcing the user to enter something in each field. We do this by modifying the Person class definition, located in app/models/person.rb. When we first open person.rb, we see that it is an unchanged subclass of ActiveRecord::Base:
class Person < ActiveRecord::Base end
We can add one of the built-in Rails validators, statements that allow us to check the integrity of the data at the application level, before it ever gets to the database level. In this case, we use validates_presence_of, naming each of the fields from our table:
class Person < ActiveRecord::Base
validates_presence_of :first_name, :last_name,
:email_address, :phone_number
end
With this in place—and without even having to restart the server—we can try adding another blank person. But now we find that Rails has stopped us, explaining the problem (for example, “Phone number can't be blank”) at the top of the form and outlining each of the offending fields in red. With this validator in place, we can be sure that all of the rows in the People table will contain valid data.
When we go to /Appointments to add a new appointment, something seems suspicious even before we click on the create button at the bottom of the page: there isn't anywhere that we can enter the person with whom we are meeting! This will cause problems, as clicking on the create button quickly demonstrates; PostgreSQL returns an error, which Rails displays for all to see. Clearly, we need to solve this problem.
The problem is that the view for creating new instances of the Appointment class (that is, app/views/appointments/new.rhtml) is missing an HTML form element named appointment[person_id]. If new.rhtml were to include appointment[person_id], it would be submitted along with the rest of the elements of the form and inserted into the database.
The thing is, appointment[person_id] should be populated from the database. Assuming that we have a variable named @people available to us, we could add something like this to new.rhtml right before the call to submit_tag:
<b>Person:</b><br />
<select name="appointment[person_id]">
<option value="">Select a person</option>
<% @people.each do |person| %>
<option value="<%= person.id %>">
<%= person.first_name %>
</option>
<% end %>
</select><br />
The above RHTML code is similar to JSP and ASP in that it embeds Ruby code inside of an HTML document. Code surrounded by <% %> is executed in place, while code surrounded by <%= %> is replaced by its return value.
The above code thus defines an HTML form element named appointment[person_id]. It then creates an option with a blank value. Next, we get into a standard Ruby idiom, iterating over the elements of a list, using person as an iterator, pulling out person.id as the value and person.first_name as the text. In other words, we create a <select> list of the people in our People table.
But where does @people come from? We have to define it, but we can do that inside of the Appointments controller object, app/controllers/appointments_controller.rb. That file contains all of the methods the scaffolding system created for us. We merely have to add one line to the new method definition:
@people = Person.find_all
Now, we know that @people is a variable we're defining, and we know that Person is a subclass of ActiveRecord::Base that hooks us to the People table in our database. The find_all method returns all of the elements in the table.
Finally, we modify our data model class, appointment.rb, adding a validator to ensure that we will have nonblank values for each of the fields:
class Appointment < ActiveRecord::Base
validates_presence_of :start_at, :end_at, :comment, :person_id
end
With all of this in place, we can begin to schedule appointments. Each appointment will be with a single person, and we can be sure that it will contain all of the data that we want. Moreover, we know that by the time PostgreSQL receives the data to be inserted, it will be valid.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- RSS Feeds
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- Developer Poll
- Dart: a New Web Programming Experience
- May 2013 Issue of Linux Journal: Raspberry Pi
- What's the tweeting protocol?
- Reply to comment | Linux Journal
58 min 21 sec ago - Reply to comment | Linux Journal
1 hour 45 min ago - Web Hosting IQ
3 hours 18 min ago - Thanks for taking the time to
4 hours 55 min ago - Linux is good
6 hours 53 min ago - Reply to comment | Linux Journal
7 hours 10 min ago - Web Hosting IQ
7 hours 40 min ago - Web Hosting IQ
7 hours 41 min ago - Web Hosting IQ
7 hours 41 min ago - Reply to comment | Linux Journal
10 hours 42 min ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




Comments
hi
i like this one.
hi
im am starting new at linux
it s realy
so thanks man. I understand it.