0

私は、AJAX を介してバックエンド サーバーを呼び出すほとんどの UI になるアプリを作成しています。ページの読み込みはほとんどありません。

たとえば、旅行を作成すると、JS は JSON オブジェクトを Padrino に (POST 経由で) 送信するだけで、Padrino は旅行オブジェクトを (ActiveRecord 経由で) 保存し、JSON 応答を返します。

うまくいくようですが、コードをクリーンアップするだけでなく、送信された値をサニタイズしたいと考えています。

これが私のPOSTコードです(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

現在、2 つのフィールド (タイトルと説明) しかありませんが、完了すると約 4 ~ 8 になります。新しい trip オブジェクトの作成方法が気に入りません。

私は使用してみました:

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

しかし、それはうまくいきませんでした。

POSTを送信するJSコードは次のとおりです。

// 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;
}

では、コードをクリーンアップ (POST アクションの冗長性を削除) し、保存する前にテキストが確実にサニタイズされるようにするにはどうすればよいでしょうか。

ありがとう

4

1 に答える 1

4

まず第一に、 attr_accessible および attr_protected 別名mass assignment を使用して、モデルを大量割り当てから保護する必要があります。

次に、「フォーム」を使用することを強くお勧めします。これにより、JavaScript を有効にしなくてもサイトを機能させることができます。

そのため、目立たないJavaScript コードを使用することも優れています。

// 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, 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'

ここでコントローラー:

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
于 2012-04-19T09:12:24.733 に答える