vendredi 24 avril 2015

many to many association mass assign checkboxes ruby on rails 4

what i want to accomplish it's almost exactly the same as this! railscast tutorial but can't get it to work.I have a courses table and a enrollments table they have a many to many relation so i have a join table called "courses_enrollments" i'd like to be able to add many courses to enrollments all at once from a form... i used a has_many_through relation and looped through all the courses in the form and for each of them i have a checkbox so i can add them to enrollments but when i save nothing happens my join table (courses_enrollments) never gets filled with the relations i want.... here are my models:

courses:

class Course < ActiveRecord::Base
    has_many :courses_enrollments
    has_many :enrollments, :through => :courses_enrollments

enrollments:

class Enrollment < ActiveRecord::Base
    has_many :courses_enrollments
    has_many :courses, :through => :courses_enrollments

and courses_enrollments:

class CoursesEnrollment < ActiveRecord::Base
    belongs_to :courses
    belongs_to :enrollments
end

and finally my enrollments form view:

<%= form_for(@enrollment) do |f| %>
  <% 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">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :state %><br>
    <%= f.collection_select(:state, Courses.all, :id, :name, {:include_blank => true}, {:multiple => false}) %>
  </div>

I also tried it like this in the form.... but nothing gets saved here either

 <% Courses.all.each do |course|%>
    <%= check_box_tag "enrollment[course_id][]", course.id %>
    <%= course.name %>
  <% end %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

i want to be able to save many records to the join table that holds the relation between the enrollments i am creating or updating and the courses i selected with the has many through association.... appreciate the help




Aucun commentaire:

Enregistrer un commentaire