has_many through & fields_for in rails

By | 23/07/2017

Took me a while to work this one out but let me paint the scene.

I have 3 models as follows:

class Student < ApplicationRecord
  has_many :education_records
  has_many :qualifications, through: :education_records
  accepts_nested_attributes_for :qualifications
class EducationRecord < ApplicationRecord

  belongs_to :student
  belongs_to :qualification
  has_many :qualifications
  has_many :students
class Qualification < ApplicationRecord

  has_many :education_records
  has_many :students, through: :education_records, inverse_of: :candidate
  belongs_to :education_record


In My view I had a form:

= form_for @student do |f|
    =f.fields_for :qualifications do |q|

and in my controller:

def student_params
  allowed_params = [:id, :student_id,
                    qualifications_attributes: [:id, :candidate_id, :university_name, :graduation_year]]

No matter what I did I keptgetting an Unpermitted Params qualification error until I read this post where it mentioned because in my model qualifications was plural, I had to ensure in my form I was using :qualifications and in the params I was allowing qualifications_attributes.

Once I changed ot the code above all was gravy:)

N.B. If the nested form doesn’t show up you’ll need to build it in your form, i.e.

=f.fields_for :qualifications, @student.qualifications.build do |q|