rails query multiple tables with has many though relation
<p>Hello i am looking for a way to query in these 4 tables to get the only products that matches users selected categories in rails 4.</p>

<p>Rails Models</p>

<pre><code>class User &lt; ActiveRecord::Base
  has_many :categories, through: :user_categories
  has_many :user_categories
end

class Product &lt; ActiveRecord::Base
  has_many :categories, through: :product_categories
  has_many :product_categories
end

class Category &lt; ActiveRecord::Base
  has_many :users
  has_many :products
end

class UserCategory &lt; ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end

class ProductCategory &lt; ActiveRecord::Base
  belongs_to :product
  belongs_to :category
end
</code></pre>

<p>Table structure</p>

<pre><code>products             
+---------------+      
| id | name     |   
+---------------+ 
| 1  | mouse    | 
| 2  | keyboard | 
| 3  | iphone 6 | 
+---------------+ 

categories
+---------------+
| id | name     |
+---------------+
| 1  | computer |
| 2  | mobile   |
+---------------+

users
+-----------+
| id | name |
+-----------+
| 1  | foo  |
| 2  | bar  |
+-----------+

product_categories
+------------------+
| id | p_id | c_id |
+------------------+
| 1  |   1  |   1  |
| 2  |   3  |   2  |
+------------------+

user_categories
+------------------+
| id | u_id | c_id |
+------------------+
| 1  |   1  |  1   |
+------------------+
</code></pre>