Reputation: 110
I am stuck again with a simple query. I have the following models
class Category < ActiveRecord::Base
has_many :item_types
has_many :items, :through => :item_types, :source => :category
end
class ItemType < ActiveRecord::Base
belongs_to :category
has_many :items
end
class Item
belongs_to :item_type
end
Now I am trying to write a query that fetches all the items that fall under a category. I've written a query like this:
Category.joins(:item_types,:items).where("category.id=?",1)
Its throwing me an error when where condition is included. I have no clue why it does that.I thought this is a very basic join i could do it myself but in vain.
Upvotes: 0
Views: 620
Reputation: 874
Category.joins(:item_types,:items).where("**categories**.id=?",1)
table name for category should be in where clause
Upvotes: 0
Reputation: 36
Category.joins(:item_types, :items).where(:item_type => {:category_id => 1})
Upvotes: 2
Reputation: 2945
It's much simpler if you want to build many-to-many association with ActiveRecord. If I clearly understand your question you should do something like this
# app/models/category.rb
class Category < ActiveRecord::Base
has_many :item_types
has_many :items, :through => :item_types
end
# app/models/item_type.rb
class ItemType < ActiveRecord::Base
belongs_to :category
belongs_to :item
end
# app/models/item.rb
class Item < ActiveRecord::Base
has_many :item_types
has_many :categories, :through => :item_types
end
# app/controllers/categories_controller.rb
def show
@category = Category.find(params[:id])
@category_items = @category.items
end
Upvotes: 0