Autocomplete forms in Rails 2.3.3

Posted by Brian in Howto, Rails (August 28th, 2009)

When Rails 2 was released, the core team dropped some of the Javascript Ajax helpers like in-place editing and autocompleting, and released them as plugins. However, if you’ve ever tried to use them with a modern Rails application, you may have encountered problems with routing and authenticity tokens. In this brief post, I’ll walk you through a trivial example that shows how to make Autocomplete work, using the advantages that Rails 2.3 has, including format responses.

First, let’s get a basic Rails app running with a Projects table with a single field, the project’s name :

 rails autocomplete
 cd autocomplete
 ruby script/generate model project name:string
 ruby script/generate resource projects
 rake db:migrate

Next, let’s load some test data.

 ruby script/runner "
 ['The Ninja project', 'The Top Secret project', 'World Domination'].each do |p|
    Project.create(:name => p)
 end
 "

Grab the autocomplete plugin from Rails’ Github repository and install it as a plugin:

 ruby script/plugin install git://github.com/rails/auto_complete.git

Our basic app is installed, but we need to implement a controller action to display projects.

Open app/controllers/projects_controller.rb and add this method:

  def index
    @projects = Project.all :limit => 10
    respond_to do |format|
      format.html
    end
  end

When the user requests HTML, we’ll show the last 10 projects created. Good enough for now. Let’s implement the layout and the view.

Open app/views/layouts/application.html.erb and build a very simple layout:

<html>
  <head>
    <title>Autocomplete</title>
    <% =javascript_include_tag :defaults %>
  </head>
  
  <body>
    <%= yield %>
  </body>
</html>

This very basic layout loads the default Javascript fiels for Rails and yields the template.

Now open app/views/projects/index.html and add this code:

<div id="search">
  <% form_tag(projects_path(), {:method => :get, :class => "form"}) do %>    
    <%=text_field_tag "query"%>
    <%=submit_tag "Search"%>
  <% end -%>
</div>
<div id="projects">
  <% if @projects.any? %>
    <ul>
      <%=render @projects %>
    </ul>
  <% else %>
    <p>There are no projects to show.</p>
  <% end %>
</div>

Here we have a list of projects, and when we click the submit button, we’ll filter the results. We’re using render here, and when you pass the render helper a collection, it looks for a partial that it can use render each of the elements in the collection.

Create app/views/projects/_project.erb and add this line:

<li><%=h(project.name)%></li>

Now we have to do the filtering in the controller. Since the search box is simply applying a filter to the list of projects, it makes sense for us to use the index action for the request. This means changing the controller’s index action slightly.

def index
  keyword = params[:query]
  if keyword.present?
    keyword = "%#{keyword}%"
    @projects = Project.all :conditions => ["name like ?", keyword], :order => "name asc", :limit => 10
  else
    @projects = Project.all :limit => 10, :order => "created_at desc"
  end
  
  respond_to do |format|
    format.html
    format.js do
      render :inline => "<%= auto_complete_result(@projects, 'name') %>"
    end
  end
end

If the query parameter comes in, then we want to filter. We build up a LIKE query and get the results. If no query parameter is present, we just get the top ten recent projects.

However, this is really messy. Let’s get that search logic out of the controller.

Open app/models/project.rb. Move the search logic into a new method:

def self.find_all_by_keyword(keyword)
  if keyword.present?
    keyword = "%#{keyword}%"
    @projects = Project.all :conditions => ["name like ?", keyword], :order => "name asc", :limit => 10
  else
    @projects = Project.all :limit => 10, :order => "created_at desc"
  end
end

Now change app/controllers/projects_controller.rb to call the method instead of doing the search:

def index
  @projects = Project.find_by_keyword(params[:query])
  respond_to do |format|
    format.html
    format.js do
      render :inline => "<%= auto_complete_result(@projects, 'name') %>"
    end
  end
end

Much better. At this point you have a non-Javascript search for your projects in a very short time.

Let’s add the autocomplete functionality. First, in the view, change the text field to this:

<%= text_field_with_auto_complete :project, :name, 
    { :name => "query" },
    {:method => :get, :url => projects_path(:format => :js) } %>

This sets up the autocomplete field to send its queries to our index action, but specifies that we should use the “js” format, perfectly appropriate for this, as it’s a Javascript-only request, so we should provide our response with Javascript.

Open the controller and modify the controller’s code so it looks like this:

def index
  @projects = Project.find_all_by_keyword(params[:query])
  respond_to do |format|
    format.html
    format.js do
      render :inline => "<%= auto_complete_result(@projects, 'name') %>"
    end
  end
end

The only real change is adding the format.js block of code. Here, we’re using Rails’ inline renderer which renders ERb code. Within that ERB, we’re calling the auto_complete_response helper provided by the autocomplete plugin to render the specially formatted list that the auto compelte text field expects. We’re using inline rendering here, but you could use a view with the .js extension. Since it’s one line, I’ll save the file I/O.

With the responder in place, the autocomplete should start working. This is a pretty simple example, but it does illustrate how to make the autocomplete plugin work in a current Rails application, without working about

Saving without callbacks

Posted by Brian in Howto, Rails, tips (August 19th, 2009)

Occasionally, you need to do something to a model without invoking callbacks. This is especially necessary for instances where you need to modify the record you just saved in an after_save callback. For example, say you want to create a hash based on the record’s ID. You won’t have the ID until after it’s been saved, and if you call self.save in an after_save callback, you’re going to end up in an endless loop.

It turns out that ActiveRecord has two private methods.

create_without_callbacks

and

update_without_callbacks

Remember that private in Ruby is less about keeping you from calling the methods and more about letting you know that you shouldn’t depend on them. With Ruby’s send method, using either of these in your application is easy.

Note that in Ruby 1.9, send doesn’t allow calling private methods, but send! does.

  class Project < ActiveRecord::Base
    after_save :create_hash_from_name_and_id

    private
      def create_hash_from_name_and_id
        self.hash = Digest::SHA1.hexdigest("#{self.id}#{Time.now.to_s}#{self.name}")
        self.send :update_without_callbacks
      end
  end

It’s my opinion that these methods should not be private. If I can skip validations with save(false), then I should be able to skip callbacks as well.

There are other patterns you can use to skip callbacks.

  class Project < ActiveRecord::Base
    attr_accessor :skip_callbacks

    with_options :unless => :skip_callbacks do |project|
      project.after_save :create_hash_from_name_and_id
      project.after_save :do_more_stuff
    end

    private
      def create_hash_from_name_and_id
        self.skip_callbacks = true
        self.hash = Digest::SHA1.hexdigest("#{self.id}#{Time.now.to_s}#{self.name}")
        self.save
      end
  end

So there you go. Go forth and skip callbacks at will.

Using a class method with or without named scopes

Posted by Brian in Howto, Rails (August 17th, 2009)

Here’s a quick one, building off of the previous post on Geokit and Named Scopes.

If you have defined a class method you want to run which operates on a collection of records, you can share it with named scopes.

class Project < ActiveRecord::Base
  validates_presence_of :name
  named_scope :completed, :conditions => {:completed => true}

  # returns array of names for projects
  def self.names
    scope = self.scoped({})
    scope.all.collect{|record| record.name}
  end
end

This allows you to do

@project_names = Project.names

Or

@project_names = Project.completed.names

If you return the scope, you can continue chaining. If you don’t return the scope, then you can’t. This comes in handy though for creating a method that returns other objects than the object you’re working with. Here’s a completely contrived example:

Say you want to find the actual hours you’ve spent on all your completed projects:

class Project < ActiveRecord::Base
  named_scope :completed, :conditions => {:completed => true}
  
  def self.tasks
    tasks = []
    self.scoped({}).all.each do |project|
      tasks += (project.tasks)
    end
    tasks
  end
  
  def self.actual_hours
    hours = 0
    tasks.each do |task|
      hours += task.hours
    end
    hours
  end

Grab the value like this:

actual_hours = Project.completed.actual_hours

Now, of course there are other ways to do this, and this particular method will result in a lot of queries. If you were doing this hours counting in a real app, you’d be better off using SQL. This example illustrates the point though. Now go build something more awesome.

Geokit and named_scope

Posted by Brian in Rails, tips (August 11th, 2009)

I discovered that the geokit_rails plugin doesn’t support named_scope. For those unfamiliar, named_scope methods can be chained to narrow down a query while only performing one query. Here’s an example:

class Business < ActiveRecord::Base
  acts_as_mappable 
  named_scope :active, :conditions => {:active => true}
  named_scope :nonprofit, :conditions => {:nonprofit => true}
end

@active_businesses = Business.active
@nonprofits = Business.nonprofit
@active_nonprofits = Business.active.nonprofit

Geokit has a really nice syntax for locating businesses within a certain distance.

@businesses = Business.find :all, :origin => "742 Evergreen Terrace, Springfield IL", :within => 10

However, you simply cannot, out of the box, use this with named_scopes. So I cannot do

@businesses = Business.active :origin => "742 Evergreen Terrace, Springfield IL", :within => 10

The way Geokit exposes itself to ActiveRecord is just not compatible.

RailsCasts to the Rescue!

Ryan Bates, Railscasts producer and all-around awesome guy, has posted a solution in which you can build your own dynamic named scopes. We can create our own scope for Geokit, because the Geokit-Rails plugin provides a public method to retrieve the distance SQL fragment.

First, we add a new named scope to our model

   named_scope :map_conditions, lambda { |*args| {:conditions => args} }

Next, we add our own method to handle the scopes.

    def self.by_location(options ={})
      scope = self.scoped({})
      scope = scope.map_conditions "#{distance_sql(options[:origin])} <= #{options[:within]}"
      scope
    end

We use this method to append our own conditions to the anonymous scope. we use the distance_sql method which takes whatever we pass in via our :origin option, and we concatonate the equality. In this case, we want distance less than or equal to our distance.

We can now do exactly what we wanted, although with modified syntax.

@businesses = Business.active.nonprofit.by_location :origin => "742 Evergreen Terrace, Springfield IL", :within => 10

Pretty amazing stuff.

Use Modules, not Inheritence to share behavior in Ruby

Posted by Brian in Howto, Rails, snacks (August 10th, 2009)

When working in Rails, I often find that several classes have the same behavior. A common approach to share code between objects is the tried-and-true method of inheritance, wherein you create a base class and then extend your subclasses from the parent. The child classes get the behaviors from the inheritance. Basically, Object Oriented Programming 101.

Languages like Java and Ruby only let you inherit from one base class, though, so that isn’t gonna work. However, Ruby programmers can use modules to “mix in” behavior.

Mixing it up and Mixing it in

Let’s say we have a Person class.

class Person
  def sleep
    puts "zzz"
  end
end

Now let’s say we need to define a Ninja. We could create a Ninja class and inherit from Person, but that’s not really practical. Ruby developers really don’t like changing the type of a class just because its behavior changes.

Instead, let’s create a Ninja module, and put the behaviors in that module.

module Ninja
  def attack
    "You are dead."
  end
end

We can then use this multiple ways.

Mixing it in to the parent class

In a situation where we would like every Person to be a ninja, we simply use the include directive:

  class Person
    include Ninja
  end

Every instance of the class now has the Ninja behaviors. When we include a module, we are mixing in its methods to the instance. We could also use the extend method, but this mixes the methods in as class methods.

Notice here that we redefined the class definition. This appends to the existing class; it does not overwrite it. This can be a dangerous technique if used improperly because it can be difficult to track down. This is the simplest form of monkeypatching.

There’s an alternative method.

Mixing in to an instance

We can simply alter the instance of an object, applying these behaviors to a specific instance and affecting nothing else.

  @brian = Person.new
  @brian.extend Ninja

Here, we use the extend method because we need to apply these as class methods to the object instance. In Ruby, classes are objects themselves. Our instance needs to be extended.

A more practical exaple – Geolocation

I was working on a project this weekend where I had several models that needed latitude and longitude data pulled in via Google’s web service. I used the GeoKit gem and the Geokit-Rails plugins to make this happen, but I soon noticed I was adding the same code to multiple classes.

acts_as_mappable
after_validation_on_create :geocode_address

def geocode_address
  geo=Geokit::Geocoders::MultiGeocoder.geocode (address)
  errors.add(:address, "Could not Geocode address") if !geo.success
  self.lat, self.lng = geo.lat,geo.lng if geo.success
end

It seemed immediately apparent that this should go in a module which could be included into my classes. However, I wanted to also make the two class method calls – the after_validation_on_create callback and the acts_as_mappable macro.

Ruby has a facility for that type of situation

self included

def self.included(base)
#
end

This method is called when a module is included into a class, and it gives you access to the class that’s doing the including. You can use this as a handle to call any class methods. With that, my geolocation module looks like this:

module Geolocation
  
  def self.included(base)
    base.acts_as_mappable
    base.after_validation_on_create :geocode_address
  end

  def geocode_address
    geo=Geokit::Geocoders::MultiGeocoder.geocode (address)
    errors.add(:address, "Could not Geocode address") if !geo.success
    self.lat, self.lng = geo.lat,geo.lng if geo.success
  end
  
end

So now any class that needs geolocation just needs to look like this:

class Business
  include Geolocation
end

class Nonprofit
  include Geolocation
end

Summary

The above problem could have been solved by using a parent class like MappableOjbect that included the code, but it then makes putting in additional behavior more difficult. Using modules to share code is the preferred way to attach behaviors to objects in your applications.