Rails 3.1 Ransack HABTM

Is HABTM Ransack supported?

Availability of models:

  • HABTM Store Categories
  • Category HABTM Stores

Can I use ransack to search the Store for one category? What does the form look like?

+8
ruby-on-rails search has-and-belongs-to-many ransack
source share
2 answers

I think the field you are trying to use will be

:categories_id_eq 

Usage will be something like this

 <%= f.label :categories_id_eq, "Category" %> <%= f.collection_select :categories_id_eq, Category.order(:title), :id, :title %> 
+13
source share

You should know that there are gotchas: while this works fine

 :categories_id_eq 

If you want to find products in any category, you can go with

 :categories_id_in 

But if you need to get products that belong to all selected categories, they will not work as expected:

 :categories_id_all 

returns null results in discussions:

Rails, Ransack: how to search for HABTM relationships for "all" "instead of" any "and" "

Convert habtm ActiveRecord request to Arel .

+5
source share

All Articles