2016-02-04 37 views
1

也許我的設置是不正確的,我會嘗試概述整個模型設計,以防萬一。在Rails中,如何設置關聯的批量添加/編輯關聯的表單?

我有以下型號,[1] Player, [2] Game, [3] Participation, [4] Workout, [5] Measurable

球員

class Player < ActiveRecord::Base 

    has_many :workouts 
    has_many :measurables, through: :workouts 
    has_many :participations 
    has_many :games 

end 

遊戲

class Game < ActiveRecord::Base 

    has_one :workout 
    has_many :participations 

end 

參與

class Participation < ActiveRecord::Base 

    belongs_to :player 
    belongs_to :game 

end 

鍛鍊

class Workout < ActiveRecord::Base 

    belongs_to :player 
    has_many :measurables 

end 

可測量

class Measurable < ActiveRecord::Base 

    belongs_to :workout 

end 

路線

resources :players do 
    scope module: :players do 
    resources :workouts 
    end 
end 

由於路線顯示我目前有鍛鍊作爲我的球員模型的嵌套資源。這在當時是有道理的,對我來說它仍然有用。鍛鍊可以由一名球員或許多球員組成。我現在遇到的問題是我想通過我的遊戲資源一次性添加/編輯許多鍛鍊的可衡量標準。我如何處理這種情況?我只是添加一個頁面到我的視圖/遊戲,一個新的動作到我的games_controller,然後添加accep_nested_attributes到我的遊戲模型?如果是這種情況,我的games_controller上構建的強大參數如何?因爲我需要允許衡量標準被接受,這是一個遊戲協會的組合嗎?

回答

1

我只是在我的視圖/遊戲中添加一個頁面,向我的games_controller添加一個新的動作,然後添加accep_nested_attributes到我的遊戲模型中?

這取決於你的用戶界面。如果你想把可衡量的東西和遊戲一起發送給你,那麼這就是要走的路。但是,如果您想分別添加可衡量項,則需要一個Games :: MeasureablesController。

如果是這種情況,我的games_controller上構建的強參數如何?

強參數通常與Active Record無關。這只是一個規則。每個發送給ActiveRecord的參數對象都必須被允許。 所以你可以爲每個對象類型編寫多個參數允許方法,然後像這樣傳遞它們。

Game.create(game_params, measurables: measurables_params) 

我也看到了從文檔,你可以允許嵌套參數 見http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

def game_params 
    params.require(:game).permit(:name, :level, measureables: [:fps, :ping]) 
end 
+0

啊,我從來沒有想過增加一個新的關聯'Game'(的has_many:衡量標準,通過::鍛鍊),然後將可衡量關聯添加到強參數。非常感謝您指出這一點。儘管我以前沒有想到它,但我感到有點蠢! – daveomcd

+0

好吧,即使沒有這種關聯,人們也可以通過'workout.measureables.create(measurable_params)'創建一個可測量。然後end rails會創建相同的2個sql查詢。但是額外的關聯更加困難 –