2011-09-03 63 views
3

我有一些問題,發佈JSON數據到我的軌道控制器,並從我的JSON數據獲取字段映射到paremeters創建我的實體。將JSON數據發佈到rails控制器?

這裏的作用是什麼樣子:

def create 
    @trip = Trip.new(params[:trip]) 
    if @trip.save 
    respond_to do |format| 
     format.json{render :json => @trip, :status => :created, :location => @trip } 
    end 
    end 
end 

下面是從web服務器的輸出:

Started POST "/trips.json" for 127.0.0.1 at Sat Sep 03 12:37:41 -0400 2011 
    Processing by TripsController#create as JSON 
    Parameters: {"title"=>"Charlie"} 
    AREL (0.5ms) INSERT INTO "trips" ("created_at", "updated_at", "title") VALUES ('2011-09-03 16:37:41.945743', '2011-09-03 16:37:41.945743', NULL) 
Completed 201 Created in 15ms (Views: 3.5ms | ActiveRecord: 0.5ms) 

正如你可以看到它的插入NULL到標題字段,我期待它從JSON數據映射到它?

這裏的HTTP請求:

Host localhost:3000 
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:6.0.1) Gecko/20100101 Firefox/6.0.1 
Accept */* 
Accept-Language en-us,en;q=0.5 
Accept-Encoding gzip, deflate 
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 
Connection keep-alive 
Content-Type application/json; charset=UTF-8 
X-Requested-With XMLHttpRequest 
Referer http://localhost:3000/trips/new 
Content-Length 19 
Cookie _tripplanner_session=BAh7ByIQX2NzcmZfdG9rZW4iMWJCVDc0YWNIeHROcmw5VC9ZVEhMdFNlR0dtTWtSVytCL0dwTi9yam1CUUU9Ig9zZXNzaW9uX2lkIiU1NzhlMDAwNmM2N2RkMTE1YTA3M2ZmMzA4NDQ0M2NmOQ%3D%3D--1c2f1fc1d7c1bd147fa1cf9cff47e77c050f51be 
Pragma no-cache 
Cache-Control no-cache 

回答

16

你的問題,你的控制器期待相關的trip是在params[:trip]參數。

更改您的JSON是

trip: { 
    title: 'Charlie' 
} 

,我認爲這會爲您解決問題。

即您的參數應該看起來像params => {:trip => {:title => 'Charlie}}

相關問題