如何通过Rails中的表单将项目添加到多对多?

问题描述 投票:0回答:1

我正在编写Rails应用程序,以处理大学课程的日程安排。我的大部分功能都可以正常运行,但是现在我正试图找出如何为课程的特定部分注册学生的方法。课程有很多部分,每个部分都有并且属于很多学生。

这里是我现在拥有的表单的视图。我将此部分放到我的学生的“显示”视图中。

<h3>Register for section</h3>

<%= form_for @student do |f| %>
  <p>Select Sections</p>
  <% @sections.each do |section| %>
    <p>
      <%= f.check_box(section) %>
      <%= f.label(section.course.course_num + section.section_letter) %>
    </p>
  <% end %>
  <p>
    <%= f.submit :value=>'Register'%>
  </p>
<% end %>

这里是控制器。

class StudentsController < ApplicationController

    def index
        @students = Student.all
    end

    def show
        @student = Student.find(params[:id])
        @sections = Section.all
    end

    def new
        @student = Student.new
    end

    def edit
        @student = Student.find(params[:id])
    end

    def create
        @student = Student.new(student_params)
        if @student.save
            redirect_to @student
        else
            render 'new'
        end
    end

    def update 
        @student = Student.find(params[:id])
        if @student.update(student_params)
            redirect_to @student
        else
            render 'edit'
        end
    end

    def destroy
    end

    private
        def student_params
            params.require(:student).permit(:student_name, :student_id, section_ids: [])
        end

end

我现在得到的错误消息看起来像这样:

NoMethodError in Students#show
Showing /home/railslab08/datavnew2/app/views/students/_add_section.html.erb where line #7 raised:
undefined method `#<Section:0x00007f8301c424b8>' for #<Student:0x00007f8301d7a948>
Trace of template inclusion: app/views/students/show.html.erb
Rails.root: /home/railslab08/datavnew2
app/views/students/_add_section.html.erb:7:in `block (2 levels) in _app_views_students__add_section_html_erb__4250272737295861047_70100323719280'
app/views/students/_add_section.html.erb:5:in `block in _app_views_students__add_section_html_erb__4250272737295861047_70100323719280'
app/views/students/_add_section.html.erb:3:in `_app_views_students__add_section_html_erb__4250272737295861047_70100323719280'
app/views/students/show.html.erb:26:in `_app_views_students_show_html_erb___4088791611087206556_70100324157940'

我需要将什么方法传递给check_box帮助程序?我不喜欢复选框,因此,在这种情况下,如果选择/组合框会更好或更容易实现,则欢迎提出建议。任何帮助表示赞赏!

ruby-on-rails ruby-on-rails-5
1个回答
-1
投票

您需要使用accepts_nested_attributes_for保存嵌套属性。在Student模型中添加

accepts_nested_attributes_for :sections

形式

= f.fields_for :sections do |sf|
  = sf.checkbox :section

此处有更多信息,https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

© www.soinside.com 2019 - 2024. All rights reserved.