Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 Ransack HABTM

Is HABTM supported by Ransack?

Having the models:

  • Shop HABTM Categories
  • Category HABTM Shops

Can I use ransack to search a Shop by a single category? What does the form look like?

like image 352
Yaniv Preiss Avatar asked Jul 23 '12 19:07

Yaniv Preiss


2 Answers

I think the field you're trying to use would be

:categories_id_eq

Usage would be something like this

<%= f.label :categories_id_eq, "Category" %>
<%= f.collection_select :categories_id_eq, Category.order(:title), :id, :title %>
like image 153
Baylor Rae' Avatar answered Nov 15 '22 18:11

Baylor Rae'


You should be aware that there are gotchas: while this workds 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 belonging to all of categories selected it wont work as expected:

:categories_id_all

returns zero results see discussions:

Rails, Ransack: How to search HABTM relationship for "all" matches instead of "any"

Convert ActiveRecord habtm query to Arel .

like image 32
prikha Avatar answered Nov 15 '22 17:11

prikha