Ruby on Rails Part 2

Here goes


Tutorial In the previous introductory Ruby on Rails article, we created an Oracle database table. In this article we shall develop a Model-View-Controller (MVC) CRUD (Create, Read, Update, and Delete functionality) application using Ruby on Rails. Rails is a combination of the following sub-projects…

  1. Model: Active Record is an object relational mapping package built on the Active Record pattern.
  2. Control: Action Controller (Action Pack package)
  3. View: Action View (Action Pack package)

Active Record integrates business objects and database tables to create a persistable domain model. Active record does not require any configuration files. Active Record uses transactions for database operations. The ActiveRecord::Base class is used to create a connection with the database, create a database record, find a database record, update a record and delete a record. Some of the methods in the ActiveRecord::Base class are discussed in following table.

Method Description
establish_connection() Establishes a connection to the database.
set_table_name() Sets the table name.
set_primary_key() Sets the primary key.
create() Creates an object and saves it as a record.
find(*) The find() method may be used with one of the following retrieval methods: Find by id: Finds a record for a specified id or a list/array of ids. Find first: Retrieves the first record that matches the specified options. Find all: Retrieves all the records that match the specified options. Some of the options that may be specified are: :conditions: An SQL fragment such as “catalogId=catalog1”. :limit: An integer specifying a limit on the number of records returned. :offset:An integer specifying the row offset to retrieve rows. For example, if :offset is 5, the first 4 rows are skipped. :select: Specifies a SELECT statement to retrieve rows. By default SELECT * FROM is used.
find_by_sql(sql) Retrieves a result set for the specifies SELECT statement.
update() Updates a record.
update_all() Updates all records.
delete() Deletes a record.

Next, we shall discuss each of these methods with an example. An example of creating an Oracle database connection with the establish_connection method is as follows:

ActiveRecord::Base.establish_connection(
  :adapter  => "oci",
  :host     => "",
  :username => "oe",
  :password => "oracle" 
   :database => “ORCL”
)

The :adapter key specifies a database adapter in lower-case. Table name and primary key may be set in a model class that extends the ActiveRecord::Base class as in following listing:

class Catalog < ActiveRecord::Base
set_table_name "catalogs" 
set_primary_key "catalogid"
end

The create method is used to create a record. For example, to add a record with values specified for column1, column2 and column3:

Catalog.create :column1 => "column1value", :column2 => "column2value", :column3 => "column3value"

The find method is used to find a record. For example, to find the first record that matches the SQL section:

find(:first, :conditions => "section = 'SQL'")

The find_by_sql method finds a result set for a specified SQL statement. An example of find_by_sql, in which a result set is created for the SQL section, is as follows:

@resultset=Catalog.find_by_sql("SELECT * from catalogs WHERE SECTION='SQL'")

The update method updates a record for the specified id. For example, the following listing updates journal and title columns of a row with id 1:

Catalog.update (1, {:journal=>'Oracle Magazine', title=>'Introduction to Ruby on Rails'} ) 

The update_all method updates all the records. For example, update all records to set journal to “Oracle Magazine” and publisher to “Oracle Publishing” like this:

Catalog.update_all "journal='Oracle Magazine',  publisher='Oracle Publishing'"

The delete method deletes a record. For example, to delete a record with id 10:

Catalog.delete(10) 

An Action Controller is made up of one or more actions (methods) that perform business logic and then either render a template or redirect to another action or a page. An action is defined as a public method and assumes that you want to render a template matching the name of the action when the method code has run. You may also redirect to an action or a page with redirect_to as in the following listing which redirects to a controller action index:

redirect_to :action=>”index” 

Redirect_to:back redirects back to the page that issued the request. A request is sent to an Action Controller from a view template with the :action key. The :action key specifies name of an action in the Action Controller as shown in following listing:

:action=>:index

The request parameters are sent to the controller action and the action code is run. The request parameters are available to a controller action with the params hash. For example, :section param may be retrieved in a controller action with params hash as shown below:

@section=params[:section] 

Each controller action results in a response that is constructed using renders and redirects. By default a controller action renders a view template with matching name. For example, an index action would render the index template. The local variables set in a controller action are available to the template rendered and a controller action may render a template other than the default template. For example, render a edit template as shown below:

render :template=>”edit” 

A controller action may render a template for another action. For example, a controller action may render template for another controller action index as shown in following listing:

render :action=>”index” 

A file may also be rendered from a controller action. For example, render a file template.rhtml as shown below:

render :file=>”template.rhtml” 

Text may be rendered in the view template that invokes a controller action with render:text as shown below:

render:text =>”Example of render text” 

A MVC Rails application consists of the following Ruby, RHTML and configuration files:

  1. View templates(.rhtml files) in the app/views directory.
  2. Model class in the app/models directory.
  3. Controller class in the app/controllers directory
  4. Database Configuration file (database.yml) in the config directory.

A MVC Ruby on Rails application may be developed either by creating the model and controller classes separately and adding scaffolding to the model class, or by creating the model and controller classes with the Scaffold generator. Scaffolding consists of controller actions, including controller logic, and corresponding view templates, which perform CRUD operations on the database using the Active Record class. If the scaffold generator is used to create the model and controller classes, the scaffolding also gets added. We shall discuss both the methods, and subsequently create example model and controller classes with the scaffold generator.

Creating Model and Controller Separately

A model class, catalog, is created with the following ruby command.

>ruby script/generate model catalog

This generates a ruby script catalog.rb in the models directory of the Rails application directory. The model class extends the ActiveRecord::Base class, which was discussed earlier. Ruby script generated with example ruby command is listed in following listing.

class Catalog < ActiveRecord::Base
end

The ‘<’ denotes that Catalog is a subclass of ActiveRecord::Base class. Scaffolding may be added to the model class with the scaffold method by adding scaffold:catalog thus:

class Catalog < ActiveRecord::Base
scaffold:catalog
end

A controller class may be created with the following ruby command:

>ruby script/generate controller catalog

A controller class, CatalogController, which extends the ApplicationController class gets generated. ApplicationController is a subclass of the ActionController::Base class. The Controller ruby script, is shown in following listing:

class CatalogController < ApplicationController
end

By default, the following actions and views get generated by the scaffold method: index, list, show, new, create, edit, update, and destroy. If the default actions views are to be overridden, create view templates corresponding to the required actions. For example, to override the default view for edit action, create a view template edit.rhtml in the views directory of the Rails application.

Creating Model, Views, Controller with Scaffold Generator

The Rails framework provides a scaffold generator to generate a model class and a controller class and add scaffolding to the model class. The syntax of the scaffold generator class is as follows.

>ruby script/generate scaffold modelname, controllername,  action1, action2.. 

In the schema generator command, variable modelname specifies the model class and variable controllername specifies the controller class. Specifying controllername is optional. Action1, action2.. specify the actions in the controller class and are also optional. The following example generates a scaffolded model class, Catalog, and a controller class using the command:

>ruby script/generate scaffold catalog

This creates a model class and a controller class where the controller class created has the plural form of the model class. The model class is listed below with Model class Catalog extending the ActiveRecord::Base class:

class Catalog < ActiveRecord::Base
end

The controller class, CatalogsController, which extends the ApplicationController class, is listed below:

class CatalogsController < ApplicationController
  def index
    list
    render :action => 'list'
  end


  # GETs should be safe (see  http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @catalog_pages, @catalogs = paginate :catalogs, :per_page => 10
  end

  def show
    @catalog = Catalog.find(params[:id])
  end

  def new
    @catalog = Catalog.new
  end

  def create
    @catalog = Catalog.new(params[:catalog])
    if @catalog.save
      flash[:notice] = 'Catalog was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @catalog = Catalog.find(params[:id])
  end

  def update
    @catalog = Catalog.find(params[:id])
    if @catalog.update_attributes(params[:catalog])
      flash[:notice] = 'Catalog was successfully updated.'
      redirect_to :action => 'show', :id => @catalog
    else
      render :action => 'edit'
    end
  end

  def destroy
    Catalog.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end

The default scaffolded actions and views that get generated are: index, list, show, new, create, edit, update, destroy.

Creating and Updating a Database Row

Next, we shall create and edit a catalog entry with the Rails MVC application. First, we start the Ruby web server WEBrick with the following command.

> ruby script/server

You can then access the web server with url http://localhost:3000:

Displays figure 1. WEBrick Web Server

You can display the list of catalog entries in the catalogs table by invoking the list action with url http://localhost:3000/catalogs/list:

Displays figure 2. Invoking the list action.

To create a new catalog entry, you click on the New catalog link. This invokes the new action. The view template corresponding to new action displays the catalog entry form. To create a new catalog entry, you specify field values and click on the Create button:

Displays figure 3. New Catalog Entry View.

This creates a new catalog entry and adds it to the list view:

Displays figure 4. List view with new row.

To edit a catalog entry, you click on the Edit link. In the edit view:modify a field value for example, you modify title, and click on the Edit button:

Displays figure 5. Edit view

The catalog entry gets modified as shown in show view:

Displays figure 6. show view.

You click on the Back button to display the list view with modified catalog entry:

Displays figure 7. Modified list view.

Congratulations! You have now created a MVC application with Ruby on Rails. You did not have to create any JSPs/HTMLs, Servlets, EJBs or configuration files so that the Ruby on Rails framework is providing you with increased ease of development.


Other stories you might like

  • Quantum internet within grasp as scientists show off entanglement demo
    Teleportation of quantum information key to future secure data transfer

    Researchers in the Netherlands have shown they can transmit quantum information via an intermediary node, a feature necessary to make the so-called quantum internet possible.

    In recent years, scientists have argued that the quantum internet presents a more desirable network for transferring secure data, in addition to being necessary when connecting multiple quantum systems. All of this has been attracting investment from the US government, among others.

    Despite the promise, there are still vital elements missing for the creation of a functional quantum internet.

    Continue reading
  • Drone ship carrying yet more drones launches in China
    Zhuhai Cloud will carry 50 flying and diving machines it can control with minimal human assistance

    Chinese academics have christened an ocean research vessel that has a twist: it will sail the seas with a complement of aerial and ocean-going drones and no human crew.

    The Zhu Hai Yun, or Zhuhai Cloud, launched in Guangzhou after a year of construction. The 290-foot-long mothership can hit a top speed of 18 knots (about 20 miles per hour) and will carry 50 flying, surface, and submersible drones that launch and self-recover autonomously. 

    According to this blurb from the shipbuilder behind its construction, the Cloud will also be equipped with a variety of additional observational instruments "which can be deployed in batches in the target sea area, and carry out task-oriented adaptive networking to achieve three-dimensional view of specific targets." Most of the ship is an open deck where flying drones can land and be stored. The ship is also equipped with launch and recovery equipment for its aquatic craft. 

    Continue reading
  • Experts: AI should be recognized as inventors in patent law
    Plus: Police release deepfake of murdered teen in cold case, and more

    In-brief Governments around the world should pass intellectual property laws that grant rights to AI systems, two academics at the University of New South Wales in Australia argued.

    Alexandra George, and Toby Walsh, professors of law and AI, respectively, believe failing to recognize machines as inventors could have long-lasting impacts on economies and societies. 

    "If courts and governments decide that AI-made inventions cannot be patented, the implications could be huge," they wrote in a comment article published in Nature. "Funders and businesses would be less incentivized to pursue useful research using AI inventors when a return on their investment could be limited. Society could miss out on the development of worthwhile and life-saving inventions."

    Continue reading
  • SEC probes Musk for not properly disclosing Twitter stake
    Meanwhile, social network's board rejects resignation of one its directors

    America's financial watchdog is investigating whether Elon Musk adequately disclosed his purchase of Twitter shares last month, just as his bid to take over the social media company hangs in the balance. 

    A letter [PDF] from the SEC addressed to the tech billionaire said he "[did] not appear" to have filed the proper form detailing his 9.2 percent stake in Twitter "required 10 days from the date of acquisition," and asked him to provide more information. Musk's shares made him one of Twitter's largest shareholders. The letter is dated April 4, and was shared this week by the regulator.

    Musk quickly moved to try and buy the whole company outright in a deal initially worth over $44 billion. Musk sold a chunk of his shares in Tesla worth $8.4 billion and bagged another $7.14 billion from investors to help finance the $21 billion he promised to put forward for the deal. The remaining $25.5 billion bill was secured via debt financing by Morgan Stanley, Bank of America, Barclays, and others. But the takeover is not going smoothly.

    Continue reading
  • Cloud security unicorn cuts 20% of staff after raising $1.3b
    Time to play blame bingo: Markets? Profits? Too much growth? Russia? Space aliens?

    Cloud security company Lacework has laid off 20 percent of its employees, just months after two record-breaking funding rounds pushed its valuation to $8.3 billion.

    A spokesperson wouldn't confirm the total number of employees affected, though told The Register that the "widely speculated number on Twitter is a significant overestimate."

    The company, as of March, counted more than 1,000 employees, which would push the jobs lost above 200. And the widely reported number on Twitter is about 300 employees. The biz, based in Silicon Valley, was founded in 2015.

    Continue reading
  • Talos names eight deadly sins in widely used industrial software
    Entire swaths of gear relies on vulnerability-laden Open Automation Software (OAS)

    A researcher at Cisco's Talos threat intelligence team found eight vulnerabilities in the Open Automation Software (OAS) platform that, if exploited, could enable a bad actor to access a device and run code on a targeted system.

    The OAS platform is widely used by a range of industrial enterprises, essentially facilitating the transfer of data within an IT environment between hardware and software and playing a central role in organizations' industrial Internet of Things (IIoT) efforts. It touches a range of devices, including PLCs and OPCs and IoT devices, as well as custom applications and APIs, databases and edge systems.

    Companies like Volvo, General Dynamics, JBT Aerotech and wind-turbine maker AES are among the users of the OAS platform.

    Continue reading
  • Despite global uncertainty, $500m hit doesn't rattle Nvidia execs
    CEO acknowledges impact of war, pandemic but says fundamentals ‘are really good’

    Nvidia is expecting a $500 million hit to its global datacenter and consumer business in the second quarter due to COVID lockdowns in China and Russia's invasion of Ukraine. Despite those and other macroeconomic concerns, executives are still optimistic about future prospects.

    "The full impact and duration of the war in Ukraine and COVID lockdowns in China is difficult to predict. However, the impact of our technology and our market opportunities remain unchanged," said Jensen Huang, Nvidia's CEO and co-founder, during the company's first-quarter earnings call.

    Those two statements might sound a little contradictory, including to some investors, particularly following the stock selloff yesterday after concerns over Russia and China prompted Nvidia to issue lower-than-expected guidance for second-quarter revenue.

    Continue reading
  • Another AI supercomputer from HPE: Champollion lands in France
    That's the second in a week following similar system in Munich also aimed at researchers

    HPE is lifting the lid on a new AI supercomputer – the second this week – aimed at building and training larger machine learning models to underpin research.

    Based at HPE's Center of Excellence in Grenoble, France, the new supercomputer is to be named Champollion after the French scholar who made advances in deciphering Egyptian hieroglyphs in the 19th century. It was built in partnership with Nvidia using AMD-based Apollo computer nodes fitted with Nvidia's A100 GPUs.

    Champollion brings together HPC and purpose-built AI technologies to train machine learning models at scale and unlock results faster, HPE said. HPE already provides HPC and AI resources from its Grenoble facilities for customers, and the broader research community to access, and said it plans to provide access to Champollion for scientists and engineers globally to accelerate testing of their AI models and research.

    Continue reading

Biting the hand that feeds IT © 1998–2022