I need to generate bills for all users (residents) in my app, the bill_controller's
resident = Resident.find_by(hostel:current_admin_user.hostel) # current_admin_user action is provided by Activeadmin to access current activeadmin user details
flash[:info] = "Bills Generated successfully"
flash[:danger] = "Bills Not generated, Please try again!"
The active admin users can generate bills, and bills will be generated
only for residents that have same hostel with admin user ! And bills
should be generated for all residents with specific hostel. check out
my code, right now it is generating only for current user(resident
logged in) . thanks !
Use where to get all residents for that hostel:
residents = Resident.where(hostel: Hostel.where(name: current_admin_user.hostel).first.id)
Loop through residents and create the bill for each resident :
residents.each do |resident| # Note here I use bill_params (because it's in your example), but I'm not totally sure it's the behavior you want resident.bills.create(bill_params) end
Please note that you were using
create so the
@bill.save your were using is unnecessary (
save anyway, see Differences between new + save and create). To check if the bill has been successfully created you could use
@bill.persisted? for instance (see : Determine if ActiveRecord Object is New Or Created).