Search code examples
ruby-on-railsnested-attributesstrong-parameters

In Rails, how do I setup form for bulk adding/editing associations of an association?


Perhaps my setup is incorrect, I'll try and outline the whole model design just in case that's the situation.

I have the following models, [1] Player, [2] Game, [3] Participation, [4] Workout, [5] Measurable

Player

class Player < ActiveRecord::Base

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

end

Game

class Game < ActiveRecord::Base

  has_one  :workout
  has_many :participations

end

Participation

class Participation < ActiveRecord::Base

  belongs_to :player
  belongs_to :game

end

Workout

class Workout < ActiveRecord::Base

  belongs_to :player
  has_many   :measurables

end

Measurable

class Measurable < ActiveRecord::Base

  belongs_to :workout

end

Routes

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

As the route shows I currently have the workouts as a nested resource for my player model. This made sense at the time, and to me it still kind of does. A workout can consist of one player or many players. The problem I'm having now is I want to add/edit many workout's measurables at once through my game resource. How do I handle this situation? Do I just add a page to my views/games, a new action to my games_controller, and then add accepts_nested_attributes for to my game model? If that's the case how are the strong parameters constructed on my games_controller? Since I need to allow measurables to be accepted which is an association of an association of game?


Solution

  • Do I just add a page to my views/games, a new action to my games_controller, and then add accepts_nested_attributes for to my game model?

    It depends on you user interface. If you want to send you measureables together with the game, then it's the way to go. However if you want to add the measureables separately you would need a Games::MeasureablesController.

    If that's the case how are the strong parameters constructed on my games_controller?

    Strong Parameters have in general nothing to do with Active Record. It's just one rule. Every parameter object send to ActiveRecord has to be permited. so you can just write multiple parameter permit methods for every object type and then pass them like this.

    Game.create(game_params, measurables: measurables_params)
    

    I see also from the doc that you can permit nested parameters See http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

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