I have a Department
parent model that is associated with a Product
and Document
model through a has_many
/ belongs_to
relationship. The Product
and Document
models are then associated to each other through a has_many :through
relationship via a ProductDocuments
join model.
As part of the associations there is a requirement that the Product
and Document
models have the same Department
parent model when being associated to each other.
Right now I'm doing the following:
ProductDocumentsController < ApplicationController
...
def create
@product = Product.find(params[:product_document][:product_id])
@document = Document.find(params[:product_document][:document_id])
if @product.department.id == @document.department.id
...
end
end
...
end
This works, however it feels inefficient as it introduces two addition database calls in the controller.
Does anyone know of a way that this can be accomplished in a more efficient way, perhaps through a validation in the model?
Any help would be greatly appreciated; thank you!