Rodrigo Zurek
Rodrigo Zurek

Reputation: 4575

Rails where clause in a many to many

i have two many to many models and another

Storetypes:

class Storetype < ActiveRecord::Base
  has_and_belongs_to_many :stores
end

Stores:

class Store < ActiveRecord::Base
  belongs_to :group  
  has_many :products
end

Groups:

class Group < ActiveRecord::Base
  has_many :stores
  has_many :storetypes
end

I need to do a query where i get all the stores on a storetype, im doing something like this:

@storetype_id = Storetype.first
@stores = @group.stores.where(@storetype_id => @group.stores)

any thoughts?

EDIT

The output i need is all the stores that belong to a certain storetype

Upvotes: 0

Views: 290

Answers (1)

Niall Paterson
Niall Paterson

Reputation: 3580

Few problems here that I'll point out.

I assume you mean Storetype.first when you say @storetype.first. You're confusing the class and an instance of the class. So say I do this:

@storetype = Storetype.first

I'm creating an instance of the class Storetype, which is your model. Get me?

So to answer your question, once I have an instance, I can now simply run

@storetype.stores 

to all the stores on that storetype. See how I went the other way to your method? I also didn't need to use the id of the storetype at all. Much easier and cleaner.

For the other part of the relationship, to get all the storetypes of a store, you simply run (with an instance of Store)

@store.storetypes

Upvotes: 1

Related Questions