2012-01-28 38 views
0

我寫了一個「類別」的模型。這裏的要求是每個類別可以歸入「類型」類別。我在做這個項目的同時學習rails,並設法通過下面的類方法(where_category_type)獲得上述工作。是否有任何軌道語法糖可以使這個更漂亮?

class Category < ActiveRecord::Base 

    #associations 
    belongs_to :category_type 
    has_and_belongs_to_many :recipes 

    def self.where_category_type category_type 
    Category.find(:all, :include => :category_type, :conditions => { :category_types => {:name => category_type }}) 
    end 

end 

所有作品等等,但我很熱衷於確保我做的事情「的軌道」,所以如果我錯過了一些語法糖的地方,會更有這一點我想知道可讀/較不詳細?

回答

1
class Category < ActiveRecord::Base 

    #associations 
    belongs_to :category_type 
    has_and_belongs_to_many :recipes 

end 

然後,而不是定義* where_category_type *類別的類的靜態方法,你可以只要致電:

Category.joins(:category_type).where('category_types.name' => 'name of your category').all 
相關問題