ruby - Rails Complex Grouping by Associations -


i creating custom form builder.

a form has_many sections.

a section has_many fields.

a field has_many user_values.

there column on user_values table called cloned_index. use when user makes duplicate of section need keep sections unique.

my question:

can me write query every section, group fields cloned_index of field's user values.

i have:

form.sections.each |section| section.fields.each do|field|   field.user_values.group_by(&:cloned_index) end 

this doesn't work , tough follow. i'm sure there's easy way i'm not seeing right now.

form.sections.joins(fields: [:user_values]).group("user_values.cloned_index")  

you need join tables group them together. above query return sections grouped cloned_index

if want group fields along sections try

fields.joins(:user_values,:section]).where({sections: {form_id: form.id}}).group("sections.id , user_values.cloned_index") 

this return fields of form grouped section id , cloned_index


Comments