Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

Pre-populate association for nested form

General • Asked by John Munyi

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 :)

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.