Search code examples
ruby-on-railsassociationsdynamic-finders

Rails dynamic finders for many to many relationships


I have a model, "recipe". Here's the model;

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

I am able to use dynamic finders to write code like this;

Recipe.find_all_by_name "spaghetti bolognaise"

but the following gives me a "NoMethodError"

Recipe.find_all_by_category 1

As you can see from the model I've had to revert to creating my own finder method for this functionality. Am I just missing something with the syntax or will dynamic finders only work on properties that are columns specific to a given model (not associations)?


Solution

  • Recipe doesn't have a column/attribute named 'category' (because it's a many-to-many association), thus the method find_all_by_category isn't generated.

    Here's what you can do

    recipes = Category.find(1).recipes
    

    It would have been different if a Recipe belongs_to :category and Category has_many :recipes. In this case:

    recipes = Recipe.find_all_by_category_id(1)
    

    Because the recipes table has a column named category_id...