我有三種模型:課程,類別和分類。多對多關聯形式與collection_check_boxes導致驗證錯誤
# course.rb
class Course < ApplicationRecord
has_many :categorisations, foreign_key: "course_id", dependent: :destroy
has_many :categories, through: :categorisations
end
#category.rb
class Category < ApplicationRecord
has_many :categorisations, foreign_key: "category_id", dependent: :destroy
has_many :courses, through: :categorisations
end
# categorisation.rb
class Categorisation < ApplicationRecord
belongs_to :course
belongs_to :category
validates :course_id, presence: true
validates :category_id, presence: true
end
場控制器具有以下PARAMS:
def course_params
params.require(:course).permit(:name, :prerequisite, :description,
:user_id, :category_ids => [])
end
我試圖通過建立課程形式的關聯關係:
<%= form_for @course do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :prerequisite %>
<%= f.text_field :prerequisite, class: 'form-control' %>
<%= f.label :description %>
<%= f.text_area :description, class: 'form-control' %>
<%= f.label :category_ids, "Category" %>
<%= f.collection_check_boxes :category_ids, Category.all, :id, :name,
{}, { multiple: true, class: 'form-control'} %>
<%= f.submit "Create a new course", class: "btn btn-primary" %>
<% end %>
然而,當我點擊提交,我得到驗證錯誤:
Categorisations is invalid
我不確定這是爲什麼?