Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drogus/25867 to your computer and use it in GitHub Desktop.
Save drogus/25867 to your computer and use it in GitHub Desktop.
class ActiveRecord::Base
# Returns hash prepared to be converted to json
#
# Can take the same options as ActiveRecord::Base#to_json
def prepare_json(options = {})
if include_root_in_json
{ self.class.json_class_name => JsonSerializer.new(self, options).serializable_record }
else
JsonSerializer.new(self, options).serializable_record
end
end
end
def update
@document = Document.find(params[:document_id])
saved = @document.update_attributes(params[:document])
respond_to do |format|
if @saved
format.html {redirect_to documents_path }
else
format.html {render :action => 'edit'}
end
format.js {render :nothing => true}
format.json { render :json => {
:document => @document.prepare_json(:methods => :errors) }
}
end
end
ActiveRecord::Base.include_root_in_json = false
//Submit form with validation
$.fn.submitFormWithValidation = function(options) {
var options = options || {};
var saved = options.saved || function (){};
var not_saved = options.not_saved || function (){};
var object_name = options.object_name || 'item';
return $(this).each(function() {
options = jQuery.extend({
type: "PUT",
requestHeader: 'application/json',
dataType: 'json',
success: function (data, status) {
var errors = data[object_name].errors;
if(errors && errors.length > 0) {
for(i in errors) {
var error = errors[i];
var field = $('form #document_'+error[0]);
if(!field.parent().is('span.field-with-errors')) {
field.wrap($('<span class="field-with-errors">'));
}
}
not_saved.call(this, data, status);
} else {
saved.call(this, data, status);
}
},
data: $(this).formSerialize()
}, options);
$.rjsAjax($(this).attr('action'), options);
});
};
//Użycie:
$('#some-form').livequery("submit", function() {
$(this).submitFormWithValidation({
object_name: 'document',
saved: function(data, status) {
//do something if form was saved
},
not_saved: function(data, status) {
//do something if form was not saved
}
});
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment