vendredi 5 octobre 2018

Beginner stuck on Ruby on Rails project "...must exist"

So my assignment asks me to generate a page that handles students, courses, and sections. I'm supposed to be using many_to_many or some similar method to be able to list all this shared data. My specific problem is that I created a new table (rails g scaffold enrollment students:references sections:references) that doesn't seem to work. when I attempt to create a new enrollment using a student and section, I get an error stating that "Section must exist" error . I have no idea where this error is coming from. The sections field in this view is only populated with existing sections, so the fact that it says "must exist" is very...confusing. Can anyone point me in the right direction to solve this? I've rebuilt this project 3 times trying different methods and am just... stuck. I'll post the relevant code, but if I'm wrong about which sections you may need to see, I'll happily post the rest.

class Enrollment < ApplicationRecord
belongs_to :section
belongs_to :student 
end

<%= form_with(model: enrollment, local: true) do |form| %>
<% if enrollment.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(enrollment.errors.count, "error") %> 
prohibited this enrollment from being saved:</h2>

  <ul>
  <% enrollment.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
 </div>
 <% end %>

<div class="field">
<%= form.label :student_id %>
<%= form.collection_select :student_id, Student.order(:student_name), :id, 
:student_id, include_blank:true %>
</div>

<div class="field">
<%= form.label :course_id %>
<%= form.collection_select :course_id, Course.order(:name), :id, :name, 
include_blank: true %>
</div>

<div class="field">
<%= form.label :sections_number %>
<%= form.collection_select :section_number, Section.all, :id, 
:section_number, include_blank:false %>
</div>

<div class="actions">
<%= form.submit %>
</div>
<% end %>

class Section < ApplicationRecord
has_many :enrollments
has_and_belongs_to_many :students, through: :enrollments       
belongs_to :course

def numsem
    "#{course.name} #{course_id}"
end
end

Aucun commentaire:

Enregistrer un commentaire