Ask A Question

Notifications

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
end

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

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

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

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 = AttendanceSheet.new
    @team = @attendance_sheet.team
    @team.users.each do |u|
      @attendance_sheet.attendances << Attendance.new(:user => u)
    end
  end

alternatively can i use somethings like

    4.times { @attendance_sheet.attendances.build }

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

Your help or guidance is appreciated cheers

Reply

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 { @attendance_sheet.attendances.build }

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|
  @attendance_sheet.attendances.build(user: u)
end
Reply

So finally i ended up with this :

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

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

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

Reply
Join the discussion
Create an account Log in

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

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

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