0

I'm writing an app that will be mostly UI calling a backend server via AJAX. Very little page loads.

So for example, when I create a trip, my JS simply sends a JSON object to Padrino (via a POST) and Padrino saves the trip object (via ActiveRecord) and returns a JSON response.

It seems to work but I want to not only clean up the code, but I want to sanitize the submitted values.

Here is my POST code (trips controller)

post :index, :provides => :json do
  response = {}
  response[:trip] = {}

  begin
      @trip = Trip.new
      @trip.title = params[:trip][:title]
      @trip.description = params[:trip][:title]

      if @trip.save
          response[:status] = "Success"
          response[:trip] = {:title => @trip.title, :description => @trip.description}
          response[:message] = "#{@trip.title} successfully saved"
      else
          response[:status] = "Error"
          response[:message] = "Error saving trip"
      end
  rescue
     response[:status] = "Error"
     response[:message] = "Error saving trip"
  end

  response.to_json
end

Currently, there is only two fields (title and description) but there will be about 4-8 when done. I don't like how I'm building the new trip object.

I tried using:

@trip = Trip.build(params[:trip])

but that did not work.

Here is my JS code that sends the POST:

// Save new trip
$("#new_trip_save_btn").click(function() {
    var self = this;
    var new_trip = get_new_trip();

    $.ajax({
        data: {trip:new_trip},
        dataType: "json",
        url: "/trips",
        type: "post", 
        success: function(res) {
            console.log(res)
        }
    });
});

......

var get_new_trip = function() {
    var self = this;
    var trip = {};
    trip.title = $("#new_trip_title").val();
    trip.description = $("#new_trip_description").val();
    trip.departure_date = $("#new_trip_departure").val();
    trip.return_date = $("#new_trip_return").val();

    return trip;
}

So what can I do to clean up the code (remove redundancy in the POST action) and ensure the text is sanitized before saving.

Thanks

cbmeeks
  • 11,248
  • 22
  • 85
  • 136

1 Answers1

4

first of all, you should protect your model from mass assignments using attr_accessible and attr_protected aka mass assignment.

Then I highly suggest to use "forms" so your site can work without javascript enabled.

So using unobtrusive javascripts code can be also nicer.

// Live watch events on form submit
$(document).on('submit', 'form[data-remote]', function(e){
  e.preventDefault();
  self = $(this);
  $.ajax({
    url: self.attr('action'),
    data: self.serializeArray(),
    type: self.attr('method'),
    dataType: 'json',
    success: function(res){ console.log(res) }
  })
});

Here the form:

/* Here the form, for dates I suggest to use a calendar */ 
/* like https://github.com/arshaw/fullcalendar */
- form_for @trip, url(:trip, :index), :'data-remote' => true do |f|
  == f.error_messages
  == f.text_field :title
  == f.text_area :description
  == f.text_field :departure_date
  == f.text_field :return_data
  == f.submit 'Send'

Here the controller:

provides :json # if all your actions in your controller respond to #json it is more dry

get :index do
  @trip = Trip.new(params[:trip])

  if @trip.save
    render :success => true, :attributes => @trip.to_json
  else
    render :success => false, :errors => @trip.errors.full_messages
  end
end
DAddYE
  • 1,719
  • 11
  • 16
  • Thanks for your response. However, my logic is to render static pages with nginx and simply use Padrino as a backend. I will be spending a lot of time on the JS UI so no JS means no access. Which some people don't like. But come on...it's 2012. lol. What are your thoughts on replacing my custom JS ajax posts with Backbone? – cbmeeks Apr 19 '12 at 12:33
  • Depends, Backbone is a great choice but if app logic isn't so complex could be better write from scratch few lines of js. My code 'live' watch all your forms with 'data-remote' attributes and convert it to an ajax request. It's a 'standard' rails-ujs/padrino-ujs call that is always useful. – DAddYE Apr 19 '12 at 12:58
  • Very true about Backbone. I'm actually rendering the index/new/edit form in one HTML page that nginx will serve. I then hide each section based on what you are trying to do. Makes it appear the page loads are instantaneous. :-) – cbmeeks Apr 19 '12 at 13:07