2012-07-12 57 views
1

我工作的一個Rails應用程序3.1.X鍵,我有以下組模型:Rails的控制器動作:自定義params中的散列

class Widget 
    include Mongoid::Document 
    field :name 
    embeds_many :comments 
end 

class ShinyWidget < Widget; end 
class DullWidget < Widget; end 

class Comment 
    include Mongoid::Document 
    field :message 
    embedded_in :widget 
end 

所以基本上我需要讓意見與關聯不同類型的小部件。在我的路線使用標準資源,如:

resources: widgets do 
    resources :comments 
end 

一個公開的網址,如GET /widgetsGET /widgets/:widget_id/comments等。但是,我想揭露了一個API添加註釋,以不同類型的部件。我想這些API的URL看起來是這樣的:

GET /shinywidgets/:widget_id/comments 
POST /shinywidgets/:widget_id/comments 

不過,我確定與具有ShinyWidgetsController和DullWidgetsController,但我想只有建立一個單一的CommentsController。由於我沒有想到的具有單CommentsController來處理不同類型的部件意見的一個很好的方式,我想這一點:

resources :widgets do 
    get 'comments', to: 'widgets#comments_index' 
    post 'comments', to: 'widgets#comments_create' 
end 

當做一個POST到/部件/:WIDGET_ID /評論params哈希存儲發佈在名爲widget的密鑰中的評論數據,而不是我期待的comment

我知道如果使用resources :comments Rails會將params哈希中的密鑰更改爲comment,但是我可以告訴Rails在給定當前設置的情況下命名該密鑰的方法嗎?

目前我已經創建註釋做這樣的事情:

def comments_create 
    widget = Widget.find(params.delete :widget_id) 
    comment = widget.comments.create(params[:widget]) 
end 

我真的很想有:

comment = widget.comments.create(params[:comment]) 

有什麼想法?

+0

此行爲沒有什麼關係的路線。你的表單決定了'params'的外觀。請張貼你的表格。 – Mischa 2012-07-12 11:51:51

+0

沒有表單,這是作爲JSON API公開的。 – codecraig 2012-07-12 11:56:23

+0

你可以顯示*那個*代碼嗎? – Mischa 2012-07-12 11:58:19

回答

2

這是目前非常錯誤的。

爲了使這項工作,因爲它應該,你應該創建一個路由這樣

resources :widgets do 
    get 'comments' => 'comments#index' 
    post 'comments' => 'comments#create' 
end 

,並張貼到這個CommentsController時,您在您的評論信息正確傳遞在prams[:comment]

你的控制器將有這樣

def create 
    widget = Widget.find(params.delete :widget_id) 
    comment = widget.comments.create(params[:comment]) 
end 
+0

這裏的問題是「API」暴露在/部件/:WIDGET_ID /評論,而不是/ shinywidgets /:WIDGET_ID /評論和/ dullwidgets /:WIDGET_ID /評論 – codecraig 2012-07-12 12:15:25

+0

你是要去使用STI的是,你可以得到ID:'widget_id'參數中的小部件,當您找到它時,評論將被分配給正確的類。 – Draiken 2012-07-12 12:28:19

+0

@codecraig爲什麼評論模型會關注它是哪種類型的構件?如果它們都是小工具,通過將評論與它關聯起來,它將正確工作 – Draiken 2012-07-12 12:31:26