适用于多对多关系的Rails动态查找器

时间:2012-02-01 18:41:22

标签: ruby-on-rails associations dynamic-finders

我有一个模型,“食谱”。这是模型;

https://github.com/mikeyhogarth/Nomelette/blob/master/app/models/recipe.rb

我可以使用动态查找器来编写这样的代码;

Recipe.find_all_by_name "spaghetti bolognaise"

但是下面给我一个“NoMethodError”

Recipe.find_all_by_category 1

从模型中可以看出,我必须恢复为此功能创建自己的finder方法。我只是遗漏了一些语法,或者动态查找器只能处理特定于给定模型的列的属性(不是关联)?

1 个答案:

答案 0 :(得分:3)

Recipe没有名为'category'的列/属性(因为它是多对多关联),因此不生成方法find_all_by_category

这是你可以做的事情

recipes = Category.find(1).recipes

Recipe belongs_to :categoryCategory has_many :recipes会有所不同。在这种情况下:

recipes = Recipe.find_all_by_category_id(1)

因为食谱表有一个名为category_id ...

的列