Reputation: 181
I have three models: Course, Category, and Categorisation.
# 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
Course controller has the following params:
def course_params
params.require(:course).permit(:name, :prerequisite, :description,
:user_id, :category_ids => [])
end
I'm trying to build the association via the Course form:
<%= 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 %>
However when I click submit I get the validation error:
Categorisations is invalid
I'm unsure why this is the case?
Upvotes: 0
Views: 196
Reputation: 714
You're not able to save any entity that relates to Categorization in database because of presence: true
action. Firstly, I think it's a better idea to validate :category_id
in the schema.rb
by category_id null: false
. And secondly, are you sure you need the Categorization model? My suggestion is to think of putting a categorizationable.rb
file in your yourApp/app/models/concerns
folder and after that using its functionality in the existing models. You can read more about concerns here. This technique is really powerful when your models need refactoring.
Upvotes: 1
Reputation: 23711
Removing the presence validation on :course_id
will fix the issue
class Categorisation < ApplicationRecord
belongs_to :course
belongs_to :category
# validates :course_id, presence: true
validates :category_id, presence: true
end
Problem:
Course is not saved but due to through association when you associate category with course rails first tries to save categorisation
but course_id is not available yet
And this is the reason presence validation fails for course_id
Solution
Removing the validation is just a workaround the actual solution will be something interesting
NOTE: Even I am facing the similar issue a few days back. we have removed validation for now. I will be interested in any better solution
Upvotes: 2