Nischay namdev Nischay namdev - 1 year ago 51
Ruby Question

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


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

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
flash[:info] = "Bills Generated successfully"
redirect_to new_bill_path
flash[:danger] = "Bills Not generated, Please try again!"
redirect_to new_bill_path


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 Source

Use where to get all residents for that hostel:

residents = Resident.where(hostel: Hostel.where(name: current_admin_user.hostel)

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

Please note that you were using create so the 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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download