Database views and Rails

When it comes to using database views then most of us think that it is difficult to use them with Rails or we may not be able to use ActiveRecord with it. Since I experimented with it in the past so I thought why not share it with you folks.

There are several situations when we would like to use database views with our Rails application like:

Situation 1:

If we have a complex SQL query that we don’t want to code in your Rails app due to performance related or any other issues.

Situation 2:

When our database guys have already spent a great amount of time writing useful views that can be used in the current app

Situation 3:

When we have some repeated query to run in every select statement to fetch data from every table. For instance
Select * from table_name where created_on < today;

In that case we would prefer to have a view with this query and call that view.

In all the above situations, it is pretty easy to use our database views with Rails.

How?

Simply create your model as you would for a table and it will work fine just like your model for a database table.

Interesting thing is, apart from viewing data using views I can even update, delete and insert data in my database tables using my views with all those ActiveRecord/ORM niceties (in Sybase) as long as each database view consists of only one table. If you are using more than one table in your database views then you can only view data but cannot do delete, update and insert operation.

I think this is really useful if we have a database that do not conform to Rails conventions but we would like to follow those conventions without changing the current database if other applications depend on it as well. Simply create views for each table in the database and use those views for our models instead of actual tables.

Those single table views (in other words updatable views) will allow us to follow Rails database conventions without changing our existing database tables while also keeping our database guys happy ;o)

(Though we also have other options if we are not following rails conventions)

NOTE: I have tried updatable views only with Sybase and would love to know about your experience with other databases.

Stored Procedures and Rails – Part 2


Continued from Stored Procedures and Rails – Part 1

Now we know how to call our good and reliable stored procedures but there is a difference when we get records from database using Rails ORM/ActiveRecord compared to a stored procedure. This requires a different approach to access records returned from a stored procedure.

Lets say we have a table orders and a corresponding model Order. We all know, how to access data using ActiveRecord, eg.

@orders = Order.find(:all, :conditions => ["some simple condition"])

then what is returned to us is an array of order objects which we can access by either using a block or a for loop. For instance,

for order in @orders
  puts order.order_name
end

but this is not possible in case if we use a stored procedure to get data on orders because we don’t get back an array of order objects instead we simply get back an array of hashes, ie. an array of records with their attributes and values. Hence, the above code will not work.
Lets say you call your stored procedure, like this

@orders = DbStoredProcedure.fetch_records("exec procedure_name 'args1', 'args2'")

as mentioned in the previous post.
Then you need to access records with a little modification within your for loop

for order in @orders
  puts order['order_name']
end

I thought this might save sometime who are new to using stored procedures.

NOTE: The only downside of using stored procedures in Rails currently is; you cannot use the Object Relational Mapping which you might have been used to by know, ie. picking all children of an order by simply typing

order.children

The best thing to do is to use stored procedures judiciously and mainly for complex logic/calculation in your database but when you want to do something simple with your data like simply showing something or a quick update then use ORM over stored procedures.

Stored Procedures and Rails – Part 1


There is no documentation in Rails about how to use stored procedures or atleast it is difficult to find where to look at. And according to DHH stored procedures is not the Rails Way to do things. DHH mentioned in his post

I want a single layer of cleverness: My domain model. Object-orientation is all about encapsulating clever. Letting it sieve half ways through to the database is a terrible violation of those fine intentions. And I want no part of it.

I somewhat agree to what DHH has to say. And that’s all fine but what if we don’t have any other option apart from using stored procedure and our stored procedure has some complex logic which we don’t want to put in our Ruby code then here is a little hack to it

ActiveRecord::Base.connection.execute("execute procedure_name")

But the above code will not return anything it will only execute your procedure, considering everything went OK.

Moreover, it’s not DRY if everytime you have to write that line of code just to call a procedure.

Here is a better way to do it:

1) Create a class and let’s call it

Class DbStoredProcedure
  your methods here .......
end

2) Create a class method within it

def self.fetch_db_records(proc_name_with_parameters)
  ActiveRecord::Base.connection.execute(proc_name_with_parameters)
end

Then simply call it as

DbStoredProcedure.fetch_db_records("exec procedure_name 'args1', 'args2', 'and so on' ")

As mentioned above, this will only execute a procedure without returning any value. To return records or values from stored procedures can use other methods provided by the AR,

class DbStoredProcedure < ActiveRecord::Base

  def self.fetch_db_records(proc_name_with_parameters)
    connection.select_all(proc_name_with_parameters)
  end

  def self.insert_update_delete_calculate(proc_name_with_parameters)
    connection.execute(proc_name_with_parameters)
  end

  def self.fetch_val_from_sp(proc_name_with_parameters)
    connection.select_value(proc_name_with_parameters)
  end

end

And then simply call it like

DbStoredProcedure.method_name("exec procedure_name 'args1', 'args2', 'and so on' ")

Sweet…

If you know a better way to do it then I would love to know your views.

Stored Procedures and Rails – Part 2

RSS Feeds + Ruby on Rails + Web App


The Feedtools library is a very comprehensive and powerful Ruby library for handling rss, atom, etc as well as caching. It makes creating, consuming and manipulating feeds a piece of cake.

It’s ideal for parsing RSS feeds in Ruby on Rails applications.

Assuming that you already have installed Ruby and Rubygem, simply run

gem install feedtools

to install the FeedTools gem

or download it from the FeedTools project page and put the untar/unzipped folder in the vendor/plugins directory of your app.

To do a very quick test, create a file called testfeed.rb and add the below code in it:

    require "RubyGems"
    require "feed_tools"

    feedurls = 'http://www.sphred.com/combined_feed'
    # If you want to fetch more than one feed then comment the above feedurls variable and   uncomment the below one.
    #feedurls = %w(http://feeds.feedburner.com/Sphred_top_10_feeds   http://feeds.feedburner.com/Sphred_site_only http://feeds.feedburner.com/Sphred_site_feature)
    my_feeds = FeedTools::build_merged_feed feedurls

    my_feeds.title = 'Sphred.com Feed'
    my_feeds.copyright = 'SPhred'
    my_feeds.author = 'Nasir '
    my_feeds.id = "http://www.sphred.com/combined_feed"

    File.open('./my_feeds.xml', 'w') do |file|
      file.puts my_feeds.build_xml()
    end

Running this file from IRB will create a my_feeds.xml file in your current directory with all the feed contents.

To show feeds on a website, you need to do a few things:
1) Put

require "feed_tools"

at the top of your controller
2) Create an action within this controller to show your feeds, lets call that action user_data

    def user_data
      @feed = FeedTools::Feed.open(params[:feed_url])
      # You can first test it with a static feed url like this
      #@feed = FeedTools::Feed.open('http://www.sphred.com/combined_feed')
    end

3) In the corresponding view add this code

  <div class="feeds">
    <h3>
      <a href="<%= h @feed.link %>">
      <%= @feed.title %></a>
    </h3>
    <p><%= @feed.description %></p>
    <% for feed in @feed.items %>
      <div class="feed_item">
        <h4>
          <a href="<%= h feed.link %>">
          <%= feed.title %></a>
        </h4>
        <p><%= feed.description %></p>
     </div>
   <% end %>
 </div>

This is all good for development environment or for small apps but once you go to production environment then you have to think of caching to avoid hitting the feed server every time before displaying feed contents.