2013-04-28 37 views
1

所以我是新來的RoR,我似乎無法做一個選擇哪裏陳述。這些是以下類:RubyOnRails - 通過關係不能做一個has_many的地方

的車型:

class List < ActiveRecord::Base 
    has_many :list_categorization 
    has_many :category, :through => :list_categorization 
end 

class ListCategorization < ActiveRecord::Base 
    attr_accessible :category_id, :list_id 

    belongs_to :category 
    belongs_to :list 
end 

class Category < ActiveRecord::Base 
    attr_accessible :name 

    has_many :list_categorizations 
    has_many :lists, :through => :list_categorizations 
end 

而且我想要做的是選擇一個給定的類別列表。我試圖做的這一個簡化版本在list_controler用下面的代碼:

class ListsController < ApplicationController 

    @lists = List.where("category.id = ?", 2) 
    end 
end 

而且具有以下觀點:

<ul class="lists"> 
    <%= render @lists%> 
</ul> 

然後下面的錯誤apears:

的ActiveRecord :: StatementInvalid in Lists#index_where

SQLite3 :: SQLException:no such column:category.id:SELECT「lists」。* FROM「lists」WHERE(category.id = 2)ORDER BY lists.created_at DESC

我在做什麼錯?感謝和最好的問候。

回答

2
@lists = Category.find(2).lists 
+0

它工作完美,謝謝! – Bparra 2013-04-28 10:10:18

2

我認爲你試圖做這樣的事情:

@lists = List.joins(:categories).where('category.id = 2') 

你可以這樣做:

@lists = Category.find(2).lists 
+0

它的工作這樣!不知道什麼時候應該使用where語句,但是..謝謝! – Bparra 2013-04-28 10:14:30

+0

當你有一堆數據,並且你想創建一個限制記錄的條件,就像一條SQL語句。 List.where(「category.id =?」,2)的問題是您試圖對用於Category對象的List對象應用條件。 Category.find(2)= Category.where('categories.id = 2') – Ghar 2013-04-28 10:23:47