All threads / Pre-populate association for nested form
Ask A Question


You’re not receiving notifications from this thread.

Pre-populate association for nested form

John Munyi asked in General

Hi so here is what i have :

class Attendance < ActiveRecord::Base
  belongs_to :attendance_sheet
  belongs_to :user

class AttendanceSheet < ActiveRecord::Base
  has_many :attendances, dependent: :destroy
  accepts_nested_attributes_for :attendances, reject_if: :all_blank, allow_destroy: true
  belongs_to :team

class User < ActiveRecord::Base
  has_many  :attendances, dependent: :destroy
  belongs_to :admin

class Team < ActiveRecord::Base
  has_many :users
  belongs_to :admin
  has_many :attendance_sheets

As you can see the attendances are nested in attendance_sheet , so when a new attendance sheet is created it has a team assigned to it depending on the user who is logged in the user had to click "Add" to populate the needed number of attendances of users for that day .

I am looking for a way since the team is already selected can all the names of the users in that team be populated all at once , current my attendance new looks like this

from an old rails version, and doesnt work

def new
    @attendance_sheet =
    @team =
    @team.users.each do |u|
      @attendance_sheet.attendances << => u)

alternatively can i use somethings like

    4.times { }

where 4 is passed dynamically as the size of the team ?

Your help or guidance is appreciated cheers

Normally you don't want to use the shovel << operator if you can help it. It's not entirely clear as to what it does, so I'd definitely suggest doing the alternate you mentioned.

    4.times { }

Build can also accept params, so you can pass in the user as you had in your original example if you wanted.

@team.users.each do |u| u)

So finally i ended up with this :

 def create
     @attendance_sheet =
     @team = Team.find(attendance_sheet_params[:team_id])
     @team.users.each do |u|
       @attendance_sheet.attendances .build(user: u)

     respond_to do |format|
         format.html { render :edit }
         format.json { render :show, status: :created, location: @attendance_sheet }
         format.html { render :new }
         format.json { render json: @attendance_sheet.errors, status: :unprocessable_entity }

and it works like magic .... cheers previously it was working but i eliminated the shovel :)

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 70,078+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.