简体   繁体   中英

How to Add has_many association field to array of models in Controller

I would like to add has_many models LoanAmtPerSvcType to LoanContract array. Below is my code, but it does not work. When i check @contracts[0].loan_amt_per_svc_type.count , it return '0'

@members.each do |c|
        @contracts << LoanContract.new(
            :customer_id => c.id,
            :season_id => @season.id,
            :loan_type_id => @loan_type.id,
            :cus_group_id => @group.id,
            contract_date: @contract_date,
            loan_duration: @loan_duration,
            inspector_id: @inspector.id,
            mgr_id: @manager.id,
            user_id: @user.id)
      end
     @contracts.each do |lc|
        lc.loan_amt_per_svc_type = [LoanAmtPerSvcType.new(customer_service_type_id: 1), LoanAmtPerSvcType.new(customer_service_type_id: 2)]
     end
render :text => @contracts[0].loan_amt_per_svc_type.count

@contracts[0].loan_amt_per_svc_type.count return 0, because you didn't save your contracts into the database. You can use LoanContract.create instead of LoanContract.new . Also with associations. If you only want to know count of loan_amt_per_svc_type use size method.

@contracts[0].loan_amt_per_svc_type.size

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM