是否有任何铁路语法糖可以使这更漂亮?

时间:2012-01-28 11:01:52

标签: ruby-on-rails

我为“类别”编写了一个模型。这里的要求是每个类别可以属于一个类别“类型”。我在做这个项目的同时学习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 个答案:

答案 0 :(得分:1)

class Category < ActiveRecord::Base

    #associations
    belongs_to :category_type
    has_and_belongs_to_many :recipes

end

然后代替定义* where_category_type * Category的类静态方法,你可以只调用:

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