A Test
has_many questions
.
You would need to update the test_params
method to reflect that:
def test_params
params.require(:test).permit(:name, :user_id, :type, :category, :description, questions_attributes: [ :id, :content, :category ] ).
merge user_id: current_user.id
end
You don't need :question
here unless you have an attribute named question
in tests
table. Also, you should be using questions_attributes
(Notice plural questions) and NOT question_attributes
(Notice singular question)
On the same lines, you need to update the fields_for
in your view as below:
<%= f.fields_for :questions do |question| %>
:questions
(Notice plural questions) and NOT :question
(Notice singular question)
UPDATE
The join model of Test
and Question
is named QuestionTest
so you should be referring it in associations as question_tests
(For has_many
)
You have incorrectly setup the associations, update them as below:
class Test < ActiveRecord::Base
has_many :question_tests ## "question_tests" and NOT "questions_tests"
has_many :questions, :through => :question_tests ## "question_tests" and NOT "questions_tests"
accepts_nested_attributes_for :questions
end
class Question < ActiveRecord::Base
has_many :answers, dependent: :destroy
has_many :question_tests ## "question_tests" and NOT "test_questions"
has_many :tests, :through => :question_tests ## "question_tests" and NOT "questions_tests"
end
Implemented Solution: Hope this helps anyone needing similar results.
tests_controller.rb
def new
@test = Test.new
end
def create
@test = Test.new(test_params)
@test.save
end
_form.html.erb
<%= form_for(@test) do |f| %>
...
<div class="field">
<%= f.label :question %><br>
<%= f.collection_check_boxes :question_ids, Question.all.to_a.collect, :id, :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Schema for join table, ensure you don't have id:false
:
create_table "question_tests", force: true do |t|
t.integer "test_id", null: false
t.integer "question_id", null: false
end