我的申请的“架构”如下: 用户有学生。 学生们有书和课程。
根据情况,我可以通过书籍/新表格将学生ID作为隐藏参数传递。我正在尝试为课程做同样的事情。当我在学生/ 2 /课程/新课时,我希望能够在创作这本书时传递“2”。我没有让它工作,当我尝试时,我得到一个未定义的方法“id”的错误。我将在我的书籍控制器上运行的相同代码行剪切并粘贴到我的课程控制器上,但没有成功。
课程控制器:
class LessonsController < ApplicationController
def new
@lesson = Lesson.new
end
def show
end
def create
@lesson = Lesson.new(lesson_parameters)
if @lesson.save
redirect_to @lesson
else
redirect_to 'lessons#index'
end
end
def index
if params[:student_id]
@student = Student.find(params[:student_id])
@lessons = @student.lessons
else
@lessons = Lesson.all
end
end
private
def lesson_parameters
params.require(:lesson).permit(:reading_notes, :writing_notes, :teaching_points)
end
end
学生管理员
class StudentsController < ApplicationController
def show
@student = Student.find(params[:id]) rescue nil
@books = Book.where(student_id: params[:id])
@book = Book.new
end
def create
@student = Student.new(student_parameters)
@student.user_id = current_user.id
if @student.save
redirect_to @student
else
redirect_to 'students#index'
end
end
def index
@students = Student.where("user_id = ?",current_user.id)
@student = Student.new
end
private
def student_parameters
params.require(:student).permit(:first_name, :last_name)
end
end
新课程的部分形式
<%= simple_form_for(@lesson, html: {class: 'form-horizontal'}) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :student_id, :as => :hidden, :input_html => {:value => @student.id } %>
<%= f.input :reading_notes %>
<%= f.input :writing_notes %>
<%= f.input :teaching_points %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
路线
resources :books
resources :users, only: [:new, :create, :show]
resources :lessons
resources :students do
resources :books
resources :lessons
答案 0 :(得分:0)
您在允许的参数中缺少:student_id
。
应该是:
params.require(:lesson).permit(:student_id, :reading_notes, :writing_notes, :teaching_points)
不要忘记允许你的参数。如果你的课程现在已经定义了student_id,那么一切都应该正常工作。
此外,您应该尝试使用嵌套对象的简单形式的另一种方式
<%= simple_form_for([@lesson, @student] ...
或者相反。