0

Usersと関連するCommentsを管理する Rails を使用して REST サーバーを作成しました。
これがルート構成です。

resources :users do
  resources :comments
end

コントローラーでは、コメントを照会して作成するためのアクションのみが必要です。交換フォーマットは JSON です。

class CommentsController < ApplicationController

  def index
    @user = User.find(params[:user_id])
    @comments = @user.comments  
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @comments }
    end
  end

  def create
    @user = User.find(params[:user_id])
    @comment = @user.comments.create!(params[:comment])
    redirect_to @user
  end

end

リモート クライアントが作成したコメントを保存したいと考えています。Androidアプリです。サーバーをテストするために、ここで提案されているように、次のcurlコマンドを試しています。

curl -X POST -d @comment1.json http://localhost:3000/users/42/comments
curl -X POST -d @comment1.json http://localhost:3000/users/42/comments.json
curl -X POST -d @comment2.json http://localhost:3000/users/42/comments
curl -X POST -d @comment2.json http://localhost:3000/users/42/comments.json

また、JSON ファイルがどのように見える必要があるかもわかりません。私が試したバリエーションは次の
とおりです。

{
  content:
  {
    message: "Let's see if this works.",
    subject: "JSON via curl"
  }
}

... またはcomment2.json

{
  message: "Let's see if this works.",
  subject: "JSON via curl"
}

特定のユーザーのコメントを確認すると、それが作成されていることがわかりますが、渡されたパラメーターとがどこかで失われています!subjectmessage

[
  {
    created_at: "2012-08-11T20:00:00Z",
    id: 6,
    message: "null",
    subject: "null",
    updated_at: "2012-08-11T20:00:00Z",
    user_id: 42
  }
]

Rails のインストールには、次の gem が含まれています。

...
Using multi_json (1.3.6) 
Using json (1.7.4)
...

質問:

  • curlまたはその他の適切なツールを使用してコメント作成をテストするにはどうすればよいですか?
4

1 に答える 1

4

でcontent-typeヘッダーを設定してみてください-H "Content-Type:application/json"。Railsは投稿パラメータをフォームデータとして探していると思います(例content[subject]='JSON via curl')。

さらに、JSONファイルは無効です。JSONキーも引用符で囲む必要があります。次のファイルを使用してください...

{
  "message": "Let's see if this works.",
  "subject": "JSON via curl"
}

そして、これらのコマンドの1つでそれを送信します...

curl -X POST -H "Content-Type:application/json" -d @comments2.json http://localhost:3000/users/42/comments
curl -X POST -H "Content-Type:application/json" -d @comments2.json http://localhost:3000/users/42/comments.json
于 2012-08-11T21:30:52.943 に答える