2012-09-13 71 views
0

我再次陷入一个简单的查询。我有以下型号带条件的多个连接3.2.7

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 

现在我试图编写一个查询,获取属于一个类别下的所有项目。我写了一个这样的查询:

Category.joins(:item_types,:items).where("category.id=?",1) 

它其中包含的条件时,抛出了我的错误。我不知道为什么会这样做。我认为这是一个非常基本的联合,我可以自己做,但徒劳无功。

+1

,你能否告诉我们错误信息? – MurifoX

回答

0

如果你想用ActiveRecord建立多对多的关联,那就简单多了。 如果我清楚地明白你的问题,你应该做的事情像找到该

# 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 
+0

nick当我使用@ category.items进行查询时,我正在获取item_types。结果查询如下所示:SELECT“categories”。* FROM“categories”INNER JOIN“item_types”ON“categories ”。“id”=“item_types” 。“category_id”WHERE“item_types”。“category_id”= 1 – Ramoji

+0

你完全改变了我的要求。我有三种模式:Category,ItemType和Item.A Category可以有许多itemtypes和许多itemtype.A ItemType属于一个category并有很多项目。一个项目属于一个ItemType ..这是我模仿我的问题。 – Ramoji

0
Category.joins(:item_types,:items).where("**categories**.id=?",1) 

表名称应该是在where子句

+0

我可否知道拒绝投票的原因.. – Rubyman

2
Category.joins(:item_types, :items).where(:item_type => {:category_id => 1}) 
+0

我的商品表没有category_id列 – Ramoji

+0

对于此错字感到抱歉 – st8998