0

私はレールが初めてで、これがどのように機能するかを数日間理解しようとしています。私の目標は、ブラウザー (別のドメイン) から JSON ファイルを Rails アプリケーションに投稿し、送信されたデータをデータベースに保存することです。

次の JQuery コードが実行されます。

$(document).ready(function() {
  $("#testbutton").click(function() {
    var params = '{"comment": "Test", "creator": "Max", "name": "Testname", "url": "www.foo.com"}';
    $.ajax({
      type: "post",
      headers: { 'X-CSRF-Token': '<%= form_authenticity_token.to_s %>' },
      accepts: "application/json",
      contents: "application/json",
      data: params,
      url: 'http://localhost:3000/pages'
      });
    });
  });

action-controller での認証トークンの検証をスキップします。

skip_before_filter :verify_authenticity_token

今、JSONを解析してデータベースに書き込むために、create-actionで何を変更する必要があるのか​​ わかりません。create-action の標準動作を使用します。

  def create
    @page = Page.new(params[:data])

    respond_to do |format|
      if @page.save
        format.html { redirect_to @page, :notice => 'Page was successfully created.' }
        format.json { render :json => @page, :status => :created, :location => @page }
      else
        format.html { render :action => "new" }
        format.json { render :json => @page.errors, :status => :unprocessable_entity }
      end
    end
  end

サーバーは Web サイトからデータを受け取りますが、解析できません。

Started POST "/pages" for 127.0.0.1 at Thu Jun 07 21:48:53 +0200 2012
Processing by PagesController#create as undefined
  Parameters: {"{\"data\": {\"comment\": \"Test\", \"creator\": \"Fam Disselhoff\", \"name\": \"Renate\", \"url\": \"www.elesenroth.de\"}}"=>nil}
   (0.1ms)  begin transaction
  SQL (67.5ms)  INSERT INTO "pages" ("comment", "created_at", "creator", "name", "updated_at", "url") VALUES (?, ?, ?, ?, ?, ?)  [["comment", nil], ["created_at", Thu, 07 Jun 2012 19:48:53 UTC +00:00], ["creator", nil], ["name", nil], ["updated_at", Thu, 07 Jun 2012 19:48:53 UTC +00:00], ["url", nil]]
4

1 に答える 1

2

次のデコード メソッドを使用して処理できます。

parsed_json = ActiveSupport::JSON.decode(params[:data])
new_obj = Whatever.new
new_obj.field1 = parsed_json["field1"]
new_obj.field2 = parsed_json["field2"]
new_obj.save

お役に立てれば。

于 2012-06-07T21:13:09.903 に答える