Martin
Martin

Reputation: 800

Rails where clause over two tables

I have the following model in rails application

category => company => store

Store has a belongs_to company and company has a belongs_to category relationship. now i want to use a where method on a store object to retrieve all stores within the same category.

I would like to have something like this

@stores.nearbys(5).where("stores.company.category_id = xxx")

can somebody give me a tip on this

Upvotes: 16

Views: 30842

Answers (3)

Erez Rabih
Erez Rabih

Reputation: 15808

Try joins with where on the joined table:

@stores.nearbys(5).joins(:company).where("companies.category_id = xxx")

EDIT:

To get the category of a store you will first have to delegate the category method to its company:

class Store < ActiveRecord::Base
 belongs_to :company

 delegate :category, :to => :company
end

Now just call the method in your query:

@stores.nearbys(5).joins(:company).where("companies.category_id = ?", self.company.id)

Upvotes: 25

Simone Carletti
Simone Carletti

Reputation: 176552

where supports nested hash.

@stores.nearbys(5).where(:company => { :category_id => @category.id }, joins: company)

Upvotes: 19

Aayush Khandelwal
Aayush Khandelwal

Reputation: 1071

you can try this

 @category = Category.find xxx

 @store = @category.company.stores

Upvotes: -1

Related Questions