html - Rails4: Formtastic3.0 , save multiple instances (for Answer models) at the same time -
html - Rails4: Formtastic3.0 , save multiple instances (for Answer models) at the same time -
i have question model , reply model.
each question can have 1 reply per user. trying preset user form reply questions, couldnt figure out how formtastic
here have far
- @questions.each |q| = q.content - ans = @user.answers.where(question_id:q.id).first.try(:content) || q.description = semantic_form_for @answers |f| = f.label q.content = f.inputs :content, placeholder: ans = f.actions
i trying hint how loop through 2 alternating resources on form? maintain getting "undefined method `model_name' class:class" @questions if try:
= semantic_form_for @questions |q| = q.input :content = q.semantic_fields_for @answer |a| = a.inputs :content = q.actions
based on railscast 198, using formtastic here effort doesn't work either:
- semantic_form_for :answer, :url => api_v1_answers_path, :method => :put |f| - @questions.each |q| - f.fields_for 'questions[]', q |ff| = q.content = ff.input = submit_tag "submit"
note:
1] have user press submit 1 time after has added/edited answers
2] if there reply present, should pre-poulated in text box
3] dont mind using simple_form gem if makes life easier
rather making form @questions
need pass single object form helper (@questions
array of questions). way accomplish though form object.
# app/forms/questions_form.rb class questionsform include activemodel::model def initialize(user) @user = user end def questions @questions ||= question.all end def submit(params) params.questions.each_pair |question_id, answer| reply = answer.find_or_initialize_by(question_id: question_id, user: current_user) answer.content = reply answer.save end end def answer_for(question) reply = answers.select { |answer| answer.question_id == question.id } answer.try(:content) end def answers @answers ||= @user.answers.where(question: questions) end end
then in controller you'd have:
# app/controllers/submissions_controller.rb class submissionscontroller < applicationcontroller ... def new @questions_form = questionsform.new(current_user) end def create @questions_form = questionsform.new(current_user) @questions_form.submit(params[:questions_form]) redirect_to # where-ever end ... end
in view you'll want along lines of:
# app/views/submissions/new.html.haml = form_for @questions_form, url: submissions_path |f| - @questions_form.questions.each |question| %p= question.content = f.text_field "questions[#{question.id}]", value: @questions_form.answer_for(question) = f.submit "submit"
this doesn't utilize formtastic @ all, it's using plain rails form helpers.
this code isn't tested not sure if works helps on right track.
html forms ruby-on-rails-4 simple-form formtastic
Comments
Post a Comment