31 Mar"Ruby" or FRuby?. Part I

Wednesday, 31 March 2010 — 08:59

ActiveRecord comes with a bunch of very useful utilities for retrieving data from your database. This is really helpful for developers without knowledge on databases. We can get data from the database using very simple commands like:

last_post = Post.find(:last)
first_post = Post.first
Post.find(:all, :conditions => "type='aType'",:limit => 5)

If you have a DBA on your team, i’m sure you will have some disputes about using Ruby, or what they call FRuby (do i need to explain what does the F means?)

All those ActiveRecord utilities are translated at the end on SQL queries, and that’s why they think we should get rid of ActiveRecord’s methods and use simple queries. ActiveRecord comes with a find_by_sql query where you just enter the query to be applied, as well as the ActiveRecord::Base.connection.execute method:

Post.find_by_sql "SELECT p.* from posts where type='aType' limit 5"

Ruby on Rails works really nice on some circumstances and what’s more, the code is really simple to read. named_scope makes our life much easier and the code much more readable than using sql queries.

#post.rb
named_scope :of_type, lambda{|post_type|
    post_type ? {:conditions =>"posts.type = #{post_type}"} : {}}
named_scope :limit, lambda { |limit| {:limit => limit}}

#posts_controller.rb
Post.of_type('aType').limit(5)

Of course this is a very simple example, but where you will really see the difference, is using associations:

#employee.rb
has_many :kids

#kids
belongs_to :school

#employees_controller
@employee.kids.map(&:school).compact #returns schools where the employee takes his children

As you guess, that will get more complicated with sql:

SELECT * from SCHOOLS s join KIDS k on k.school_id = s.id join EMPLOYEES e on e.id = k.employee_id where e.name="andrew"

and this is still readable, but i’m sure things can get more and more complicated. So there is the question, ruby, or FRuby. What would you think is faster?

Comentarios

Añade tu comentario




(textile habilitado)
Negrita: *Google*
Enlace: "google.com":http://www.google.com
Imagen: !http://ggomeze.com/images/avatar.png!

ó Cancelar