所以基本上我做了一个像应用程序一样的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
非常感谢阅读。
感谢您的帮助,但是您所建议的更改没有发生。 –