【发布时间】:2017-02-25 06:20:24
【问题描述】:
所以基本上我正在制作一个类似于应用程序的谷歌表单,基本结构由一个用户一旦登录就可以创建一个表单,每个表单有多个问题,每个问题都有多个答案。
所以我正在做的是,当创建一个表单时,它也会让您创建该表单将包含的问题(该部分已经实现),然后,因为每个表单的显示视图是将要公开(因此您不必注册即可回答表单)我希望它包含答案模型的表单,其中包含每个问题的每个答案的字段。
这是我到目前为止所做的。
路线
devise_for :users
root 'forms#index'
resources :forms
post 'forms/new'
表格模型
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
问题模型
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
这是我想要显示表格以回答表格中的每个问题的视图,但我遇到了问题。
<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 模型的表单。
这是 repo 的链接,如果您想查看其他内容:https://github.com/sebasdeldi/Formularia
非常感谢您的阅读。
【问题讨论】:
标签: html ruby-on-rails ruby forms web-services