Skip to content

Instantly share code, notes, and snippets.

@staycreativedesign
Last active August 24, 2017 01:04
Show Gist options
  • Save staycreativedesign/4f481d2c96be2de44374d7b4a791073e to your computer and use it in GitHub Desktop.
Save staycreativedesign/4f481d2c96be2de44374d7b4a791073e to your computer and use it in GitHub Desktop.
class Questionnaire < ApplicationRecord
has_many :questions
has_many :member_questionnaires
has_many :users, through: :member_questionnaires
accepts_nested_attributes_for :question
end
class Question < ApplicationRecord
belongs_to :questionnaire
has_one :answer
end
class Answer < ApplicationRecord
belongs_to :question
end
%h1
questionnaires#show
= form_for @questionnaire do |f|
= @questionnaire.questions.each do |question|
%h1
= question.description
- fields_for :question, question.create_answer do |answer|
= answer.text_field :description
#what im trying to do... iterate over the questions and then have a text_field for the answers
# show the question.description and below that show a answer text_field ( the user cannot edit questions )
resources :questionnaires, only: [:index, :edit, :update] do
resources :questions, only: [] do
resources :answers, only: [:edit, :update, :create, :new], shallow: true
end
end
before(:each) do
@user = create_fake_member
q = create(:questionnaire)
4.times do
create(:question, questionnaire: q)
end
end
@nilbus
Copy link

nilbus commented Aug 24, 2017

27     - fields_for :question, question.create_answer do |answer|

A few things concern me about this line:

  1. question.create_answer is going to create a new answer in the database every time a user loads the page, not just when the form is submitted. I think what you want is question.build_answer.
  2. fields_for should be called on the form variable f or whatever fields_for fields variable it's nested under.
  3. Appending _fields to the fields_for block variable names will help distinguish model instances from field builders.
  4. You're saying these are fields for a :question, but then you name the variable answer. These should match. I think instead you want a separate fields_for for each level of russian dolls:
= form_for @questionnaire do |f|
  = @questionnaire.questions.each do |question|
    - f.fields_for :question, question do |question_fields|
      - question_fields.fields_for :answer, question.build_answer do |answer_fields|
        = answer_fields.text_field :description

Maybe that'll get you closer… this is all off the top of my head, untested. For further reading and understanding, these should be helpful:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment