所以基本上我做了一個像應用程序一樣的Google窗體,基本結構由一個用戶創建一個窗體,一旦登錄,每個窗體都有多個問題,每個問題都有多個答案。Ruby on Rails在不同的視圖上嵌套窗體
所以我在做的是,當一個表單被創建時,它使你也創建了該表單將包含的問題(該部分已經實現),然後,由於每個表單的顯示視圖將會公開(所以你不必爲了回答表格而註冊)我希望它包含答案模型的表單,其中包含每個問題的每個答案的字段。
這是我迄今爲止所做的。
ROUTES
devise_for :users
root 'forms#index'
resources :forms
post 'forms/new'
FORM MODEL
class Form < ActiveRecord::Base
has_many :questions, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:body].blank? }
end
QUESTION MODEL
class Question < ActiveRecord::Base
belongs_to :form
has_many :answers
accepts_nested_attributes_for :answers, :allow_destroy => true, :reject_if => lambda { |a| a[:body].blank? }
end
應答模型
class Answer < ActiveRecord::Base
belongs_to :question
end
因爲我使用嵌套的屬性,我所有的管理從表單控件
class FormsController < ApplicationController
before_action :authenticate_user!, only: [:index]
def index
@forms = Form.all
end
def new
numberOfQuestions = 0
if params[:numberOfQuestions]
numberOfQuestions = params[:numberOfQuestions].to_i
end
@form = Form.new
numberOfQuestions.times { @form.questions.build }
end
def create
@form = Form.new(form_params)
@form.user = current_user
if @form.save
redirect_to root_path, notice: "Form correctly created"
else
render :new, notice: "Form submition failled"
end
end
def show
@form = Form.find(params[:id])
questionsId = @form.questions.collect(&:id)
numberOfAnswers = questionsId.size
(0..numberOfAnswers-1).each do |i|
question = Question.find(questionsId[i])
question.answers.build
end
end
def destroy
@form = Form.find(params[:id]).destroy
redirect_to root_path
end
private
def form_params
params.require(:form).permit(:title, :user_id, questions_attributes: [ :body, :id, :form_id, answers_attributes: [ :body, :id, :question_id]])
end
end
,這是圖,其中我想顯示的形式回答形式中的每個問題,但是,在我M有麻煩。
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1><%= @form.title %></h1>
<ol>
<% @form.questions.each do |question| %>
<li><%= question.body %></li>
<% end %>
</ol>
<%= form_for @form do |f| %>
<%= f.fields_for :questions do |builder| %>
<% builder.fields_for :answers do |ansBuilder| %>
<div class="form-group">
<%= ansBuilder.text_field :body, class: "form-control", placeholder: "Answer the question" %>
</div>
<% end %>
<% end %>
<div class="form-group">
<%= f.submit class: "btn btn-primary", value: "Send Answer" %>
</div>
<% end %>
</div>
</div>
</div>
在其中我的代碼,則我是期待它(在./forms/1例如)示出了針對每個的相應形式在展會路徑問題爲每個表單字段中的點,但它只是不顯示Answer模型的表單。
這是回購的鏈接,如果你想看看別的東西:https://github.com/sebasdeldi/Formularia
非常感謝閱讀。
感謝您的幫助,但是您所建議的更改沒有發生。 –