Search code examples
ruby-on-rails-4activerecordnested-attributeshas-many-through

passing parameter in has_many through association


I have a class Test, Question, Testquestion associated by has_many through

class Test
  has_many :testquestions
  has_many :questions, through: :testquestions
end

class Question
  has_many :testquestions
  has_many :tests, through: :testquestions
end

class Testquestion
  belongs_to :test
  belongs_to :questions
end

While creating a Test i want to pass a value of column order of Testquestion.

def create
   Test.create(test_params)
end

def test_params
  params.require(:test).permit(:testname,question_attributes:[:questionname])
end

How should i pass value of order column so that associated model(Testquestion) get updated.


Solution

  • There's no way to do it that way, you will need to take a longer path.

    1. Don't forget to add accepts_nested_attributes_for to your assossiations, so that nested operations would actualy work.
    2. Check that you have added accepts_nested_attributes_for :question to Testquestion.
    3. Get your params structured right.

    Something like this:

    {
      test: {
        testname: 'someName',
        testquestion_attributes: {
          order: someOrder,
          question_attributes: {
            questionname: 'someName'
          }
        }
      }
    }
    
    1. Require your params.

    params.require(:test).permit(:testname, testquestion_params: [:id, :order, :_destroy, question_params: [:id, :questionname])

    p.s. sidenote: you should really aquire a habbit of naming your fields and variables in snake_case and your classes in CamelCase.