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