0

I have the following models

Document
has_many :document_categorizations
has_many :document_categories, through: :document_categorizations

DocumentCategory
has_many :document_categorizations
has_many :documents, through: :document_categorizations

DocumentCategorization
belongs_to :document_category
belongs_to :document

In my index action, I can filter the documents by category...

def index
  if params[:category_id].nil?
    @documents = Document.page(params[:page]).per(15)
  else
    @documents = DocumentCategory.find(params[:category_id]).documents
    @category = DocumentCategory.find(params[:category_id])
  end    
  ....
end

I can't use DocumentCategory.find(params[:category_id]).documents anymore because I just added kaminari for pagination and I need to make the query at the Document model not DocumentCategory.

How can I query for documents of a certain category?

leonel
  • 10,106
  • 21
  • 85
  • 129
  • What are you trying to accomplish? It almost looks like `DocumentCategorization` is unnecessary – varatis Jul 03 '12 at 17:36
  • Wait, I thought `kaminari` worked on a relation. It seems like there isn't a reason that shouldn't work. Am I missing something? – Azolo Jul 03 '12 at 18:27
  • @varatis I need DocumentCategorization because a document can belong to many categories. – leonel Jul 03 '12 at 18:53
  • @Azolo What I have currently does work. but how can I setup pagination for `DocumentCategory.find(params[:category_id]).documents` or maybe I need to modify that query to add pagination to it. – leonel Jul 03 '12 at 18:55
  • @leonel It seem like this is a HABTM situation then, and you are not setting up your tables correctly. http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many – varatis Jul 03 '12 at 19:08
  • @varatis http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many – leonel Jul 03 '12 at 19:15
  • `DocumentCategory.find(params[:category_id]).documents.page(params[:page]).per(15)` Doesn't work? – Azolo Jul 03 '12 at 20:10

1 Answers1

1

Ah! So easy. That's what happens when you code several hours straight. I think I just needed to take a break and gain a little perspective, all of the sudden it just hit me.

@category = DocumentCategory.find(params[:category_id])
@documents = @category.documents.page(params[:page]).per(15)
leonel
  • 10,106
  • 21
  • 85
  • 129