I have a tutorials model that looks like this:
class Tutorial < ActiveRecord::Base
attr_accessible :content, :title
has_many :tutorial_categories
end
and a tutorial_category model that looks like this:
class TutorialCategory < ActiveRecord::Base
attr_accessible :name, :tutorial_id
belongs_to :tutorial
end
When I know the tutorial_category via something like @tutorial_category = TutorialCategory.find(params[:id])
How can I get all the tutorials that belong to that tutorial category. Put another way, once I know @tutorial_category.name, I want all tutorials that have the same tutorial_category.name set.
Do I need to use a join or include to do this?
First you’re using the wrong type of relationship here. You’re trying to model a
many to manyrelationship with amany to onesetup. I’d setup your models like the following. This assumes you have a join table calledcategories_tutorialswith the fieldscategory_idandtutorial_id. Also note I changed the name of your categories model as it was very close to the conventional Rails join table syntax.To find all the Tutorials for a given category you can now do something like the following: