Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
3 total  XML / RSS feed 

Displaying ActiveRecord validation errors from AJAX requests

I haven’t been able to find anything built into Rails to present errors from model validation when a request is sent via AJAX.

So I came up with this handly little hack, which I’ve put in my application.rb file.

def render_javascript_alert_for_errors_on(object)
  errors = object.errors.full_messages
  alert_text = errors.collect { |error| '-' + error }.join("\n")
  render :update do |page|
    page.alert alert_text
  end
end


This takes the object and displays a nicely-formatted version of all the errors on that object, taking advantage of inline RJS to render the javascript to create an alert().

It works perfectly, but it still feels a little “hacky” to me. Any better ideas?

ActiveRecord DOM IDs

The solution—or at least a nice, cheap bandaid that can be applied easily, consists of adding a method to ActiveRecord::Base to help generate these ids without any brainpower involved.

Here’s a very simple implementation that I use in my projects, courtesy of Jamis Buck:



class ActiveRecord::Base
  def dom_id(prefix=nil)
    display_id = new_record? ? "new" : id
    prefix ||= self.class.name.underscore
    prefix != :bare ? "#{prefix.to_s.dasherize}-#{display_id}" : display_id
  end
endSo, you can do stuff like this in your views:

<ul>
<% @entries.each do |entry| %>
  <li id='<%= entry.dom_id %>'>
    <%= entry.body %>
  </li>
<% end %>
</ul>And stuff like this in your controller:

def remove_entry
  entry = JournalEntry.find(params[:id])
  update_page do |page|
    page[entry.dom_id].remove
  end
end

Debugging RJS

<script>
Ajax.Responders.register({
  // log the beginning of the requests
  onCreate: function(request, transport) {
    new Insertion.Bottom('debug', '<p><strong>[' + new Date().toString() + '] accessing ' + request.url + '</strong></p>')
  },

  // log the completion of the requests
  onComplete: function(request, transport) {
    new Insertion.Bottom('debug', 
    '<p><strong>http status: ' + transport.status + '</strong></p>' +
    '&lt;pre>' + transport.responseText.escapeHTML() + '&lt;/pre>')
  }
});
</script>

<div id="debug"></div>
« Newer Snippets
Older Snippets »
3 total  XML / RSS feed