Blog

Showing posts with label active-record. Show all posts
Showing posts with label active-record. Show all posts

Tuesday, July 26, 2011

Run a SQL query within Ruby on Rails

ActiveRecord::Base.connection.execute(your_sql_statement)

Friday, October 22, 2010

Rail's ActiveRecord: include vs join

Confused when to use the :include vs. :join option? Remember these points:

  • join does not load the association into association
  • include does, it loads each association into memory
  • include is not compatible with select option
  • use include when the association is referenced
  • example use with join, doing a dynamic count on an association
  • or when the association is not referenced

Thursday, October 21, 2010

ActiveRecord::Base#becomes

An ActiveRecord method I did not existed: becomes.

Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company) to render that instance using the companies/company partial instead of clients/client. Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either instance will affect the other.

Wednesday, September 15, 2010

Custom default attribute in ActiveRecord

When I need a default value for a ActiveRecord attribute often I will resort to using a plugin. But in reality, initializing an attribute in the #after_initialize callback is often the simplest thing that works:

class Tweet
  def after_initialize
    self.message ||= "I'm Tweeting"
  end
end         

Saturday, September 11, 2010

How to get the options for a named_scope

class Video < ActiveRecord::Base
  named_scope :highest_scores, :order => "score DESC, id"
end

Video.highest_scores.proxy_options # => {:order=>"score DESC, id"}

Wednesday, September 8, 2010

Class Methods Called Against Associations in Active Record

Did you know you can call class methods against associations? Admittedly this is a trivial example, but here goes:


Class methods also work against named scopes. I will provide a "good" example of this later in the week.

Please note this blog is no longer maintained. Please visit CivilCode Inc - Custom Software Development.