Each Loop in Rails 4 Controller to create new instance variable -


i have parent form (lead) , child form (quotemetal) (which rendered multiple times on same submit). information forms gets written respective data tables, need information child forms perform query , return values. have forms created , controller writes information data tables.

i need making query results each of child forms accessing them in views. here have.

class leadscontroller < applicationcontroller    def index     @lead = lead.new     @quote_metal = @lead.quote_metals.build   end    def create     #raise params.inspect     @lead = lead.create!(lead_params) #write data tables (which works)     @lead.quote_metals.each |f|       @metal = metal.calculate_metal(f).first #here problem is!     #calculate_metal query located in model     end   end    def show   end  private      def lead_params         params.require(:lead).permit([:name, .....              quote_metals_attributes: [:id...],       quote_melees_attributes: [:shape...],       quote_diamonds_attributes: [:shape...]       ])     end  end 

and view:

<div class='container'>   <div class="row">     <div class='col-sm-3 col-sm-offset-2'>       <h3 class="text-center">your search: </h3>     </div>     <div class='col-sm-5'>         <h4 class="text-center">returning estimates <%= @metal.metal %> setting        weighing <%= @metal.weight %> <%= @metal.unit %>. paying        <%= number_to_currency(@metal.price, precision: 2) %> per <%= @metal.unit %>.</h4>     </div>   </div> 

actions on quotemetal instances should handled in quotemetal class. so, replace:

@lead.quote_metals.each |f|   @metal = metal.calculate_metal(f).first #here problem is!     #calculate_metal query located in model end 

with:

@lead.quote_metals.each |f|   f.create end 

and in quotemetal class, can use before_save callback , perform calculation there. keep in mind invoke calculate_metal every time quotemetal saved or updated.

even better use accepts_nested_attributes_for in lead model quote_metals can automatically created when leads created. see rails documentation here. approach, eliminate above 3 lines in controller, still need callback in quotemetal class perform custom calculation.

separately, aware call create! raise exception if validation fails. not sure intend that.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -