シンプルなコントローラーで:
def new
@product = Product.new
respond_to do |format|
format.html #new.html.erb
format.json { render json: @product}
end
end
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: "Save process completed!" }
format.json { render json: @product, status: :created, location: @product }
else
format.html {
flash.now[:notice]="Save proccess coudn't be completed!"
render :new
}
format.json { render json: @product.errors, status: :unprocessable_entity}
end
end
end
単純な ajax リクエスト
$("h1").click ->
$.post
url: "/products/"
data:
product:
name: "Filip"
description: "whatever"
dataType: "json"
success: (data) ->
alert data.id
新しい製品を送信しようとしていますが、サーバーが応答します
[2013-07-09 18:44:44] 不正な URI `/products/[object%20Object]' のエラー。
データベースでは何も変更されません。/products uri を取得する代わりに、prducts/[oobject] を取得するのはなぜですか? 何が悪いの?