Nischay namdev Nischay namdev - 5 months ago 8
Ruby Question

Need to genrate bills for all users in rails, what should be create method?

Hi,

I need to generate bills for all users (residents) in my app, the bill_controller's

create
method looks like :

def create
resident = Resident.find_by(hostel:current_admin_user.hostel) # current_admin_user action is provided by Activeadmin to access current activeadmin user details
@bill=resident.bills.create(bill_params)
if @bill.save
flash[:info] = "Bills Generated successfully"
redirect_to new_bill_path
else
flash[:danger] = "Bills Not generated, Please try again!"
redirect_to new_bill_path

end
end



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 !

Answer

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 (create calls 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).