【发布时间】:2015-12-09 07:42:12
【问题描述】:
我有三个模型:课程、问题和答案。
我要做的是在显示课程视图上显示问题并允许用户为每个答案创建答案。但是,我不确定最好的方法。
我在lesson#showview 上尝试了这种方法:
<% @questions.each do |question| %>
<%= question.content %><br /><br />
<%= simple_form_for :answers do |f| %>
<%= f.input :content %>
<%= f.hidden_field :question_id, :value => question.id %>
<%= f.button :submit %>
<% end %>
<% end %>
使用此代码,我收到错误param is missing or the value is empty: lesson
Answer 有两个字段:content、question_id。
我的另一个顾虑是我希望它对用户友好,所以如果有多个问题,应该有多个输入框用于答案(每个问题一个)和一个提交按钮(所以多个答案可以一次发布)。
我认为我的方法很糟糕,但我不知道该怎么做,所以任何帮助都将不胜感激。
这是我目前所拥有的:
型号:
class Lesson < ActiveRecord::Base
has_many :questions, dependent: :destroy
has_many :answers, through: :questions
accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true
end
class Question < ActiveRecord::Base
belongs_to :lesson
has_many :answers, dependent: :destroy
end
class Answer < ActiveRecord::Base
belongs_to :question
end
课长
class LessonsController < ApplicationController
def show
@questions = @lesson.questions
end
# PATCH/PUT /lessons/1
# PATCH/PUT /lessons/1.json
def update
respond_to do |format|
if @lesson.update(lesson_params)
format.html { redirect_to @lesson, notice: 'Lesson was successfully updated.' }
format.json { render :show, status: :ok, location: @lesson }
else
format.html { render :edit }
format.json { render json: @lesson.errors, status: :unprocessable_entity }
end
end
end
private
def lesson_params
params.require(:lesson).permit(:name,
answers_attributes: [:id, :content, :question_id]
)
end
end
routes.rb
resources :lessons
post '/lessons/:id', to: "lessons#update"
【问题讨论】:
-
你应该看看处理嵌套表单的 Cocoon gem...
-
您的代码正在中断,因为您没有在 before_action 中调用“set_lesson”方法。将
before_action :set_lesson放在控制器的顶部。 -
该代码在控制器中,如果缺少,视图将不会显示显示视图。
-
你没有发布它:)
-
你试过这个
simple_form_for question.answers.build而不是simple_form_for :answers吗?
标签: forms ruby-on-rails-4