V
V
vadimstroganov2015-09-12 15:23:09
Ruby on Rails
vadimstroganov, 2015-09-12 15:23:09

How to make dynamic form generation interact with different models?

Hello! Please suggest / direct me in the right direction how to make such a form.
There are two Question and Answer models.
Accordingly, questions are stored in questions, and possible answers are stored in answer.
I made a form for editing Question:

<%= simple_form_for @question do |f| %>
  <%= f.input :question,    :label => 'Вопрос' %>
  <%= f.input :score,         :label => 'Количество баллов' %>
  # а тут должны проявлять инпуты для ответов(ответов может быть все время разное количество) они хранятся в отдельной таблице, они связаны по id
<% end %>

How to implement this? Let's say that initially one field for the answer appears, and with the button to add additional fields (the second third, etc.), and how is it all put together and sent? ..

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
Jeiwan, 2015-09-12
@Jeiwan

api.rubyonrails.org/classes/ActiveRecord/NestedAtt...
api.rubyonrails.org/classes/ActionView/Helpers/For...
https://github.com/nathanvda/cocoon
But this is a rather hemorrhoidal topic, you will have to suffer. I advise you to look for tutorials on accepts_nested_attributes, fields_for. Also, this video can help: https://youtu.be/QhdzE1yNs-0?t=1m20s

A
Anton Dyachuk, 2015-09-13
@Renius

First, you have questions and answers, for example questions has_many answers,
then you are available with static mode (one field for an answer in your terms)

<%= f.fields_for :answers, @question.answers.new do |answer_fields| %>
    <%= answer_fields.text_area :text %>

Similarly, for the existing answers of the question
<%- @question.answers.each do |answer| %>
<%= f.fields_for :answers, answer do |answer_fields| %>
    <%= answer_fields.text_area :text %>
#etc

Secondly, you manually need to design a form to dynamically add a form if you want to add a new answer form to the question via javascript
Or save the current question as standard, and re-render the form in which there will be fields for existing answers and fields for a new answer
Thirdly, you need accepts_nested_attributes :answer_attributes to serve answers nested in questions
All of this is written here in general terms

J
jarosluv, 2015-09-17
@jarosluv

The correct approach for creating forms that involve multiple models is to use Form Objects . I suggest you google about this topic, and also pay attention to these two gems (read the disclaimers):
https://github.com/apotonick/reform
https://github.com/railsgsoc/actionform

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question