2014-10-07 30 views
0

我是rails新手。 我可以創建一個控制器,將採取JSON數據和更新多個表中的數據庫?此控制器將在視圖中進行修剪。創建一個軌道控制器,它將更新db中的多個表格

我做了以下內容: - 的routes.rb:

post '/data' => 'data#submit' 

應用程序/控制器/ data_controller.rb:

class DataController < ApplicationController 
     def submit 
     data = JSON.parse request.body.read 
     puts data 
     end 
    end 

然後發送POST請求

RestClient.post "localhost:3000/submit_result", data.to_json, {:content_type => :json} 

但這gving錯誤

ActionController::RoutingError (uninitialized constant DataController) 
+0

您的URL不一致,/ data和/ submit_result。我認爲這是您的帖子中的錯誤,因爲錯誤消息意味着您擊中了正確的路線。 – Martijn 2014-10-07 07:31:47

+0

分享您的路線 – 2014-10-07 07:46:15

回答

1

您需要創建它你的config/routes.rb文件的路徑。

如果你只會有一個動作,定義會像

resource :data, only: [] do 
    post :submit 
end 

only: [] =>這使得不是正在創建的默認CRUD操作。

然後在你的控制器,你可以做到以下幾點:

class DataController < ApplicationController 
    def submit 
    data = JSON.parse params[:some_key] 
    puts data 
    render nothing: true # this will avoid view rendering 
    end 
end 

你休息的客戶應該做這樣的呼籲:

RestClient.post "localhost:3000/data/submit", data.to_json, {:content_type => :json} 

關於您是否可以更新由該控制器多個表:是, 有可能的。

假設你按照下面的格式發送數據:

RestClient.post 「本地主機:3000 /數據/提交」,{用戶:{名稱: '約翰'}作用:{名稱: '管理員' }} .to_json,{:CONTENT_TYPE =>:JSON}

然後,在你的控制器,你可以創建一個用戶和一個角色,根據接收到的PARAMS:

class DataController < ApplicationController 
    def submit 
    User.create params[:user] 
    Role.create params[:role] 
    render nothing: true # this will avoid view rendering 
    end 
end 

反正這可能很快變得複雜的控制器的代碼。最好的方法是創建一個接收參數並創建所需內容的新課程。

class DataController < ApplicationController 
    def submit 
    MassDataCreator.create(params) 
    render nothing: true # this will avoid view rendering 
    end 
end 

這樣做的好處是控制器代碼看起來更清晰,你可以寫爲創建該數據的新類的單元測試(它總是更容易測試與單元測試單個類比通過一個控制器集成測試)

+0

嗨費爾, 根據我的理解資源意味着它在db中的某個表。數據不是一個表,它是一個json數據,它包含用於更新多個表的條目。 – anamika 2014-10-07 07:37:08

+0

路線。rb只定義了你的url和爲特定url調用的controller/action之間的映射。模型是那些在數據庫中有關聯的表。 – Fer 2014-10-07 07:40:00

+0

Hi Fer, 在mkaing更改路由和控制器後,我收到錯誤「ActionController :: RoutingError(沒有路由匹配[POST]」/ data/submit「):」 – anamika 2014-10-07 08:56:54

相關問題