Topic: habtm filter by category

my models:

class Exercise < ActiveRecord::Base
  has_and_belongs_to_many :categories
  has_and_belongs_to_many :subcategories
class Subcategory < ActiveRecord::Base
  has_and_belongs_to_many :exercises
class Category < ActiveRecord::Base
  has_and_belongs_to_many :exercises

  def list
    sort_init 'title'
    @category = @params['category']
    @subcategory = @params['subcategory']
    @exercises = Exercise.find(:all, :order => sort_clause)   
    @categories = Category.find_all
    @subcategories = Subcategory.find_all

what :conditions clause would i, or should i put to return only the exercises that are associated to the id @params['category']

i have my exercises_categories table keeping track of all the categories assigned to each exercise, but i need to be able to find and display all exercises associated to any given category.

i 'think' it's means doing something like @exercises = Exercise.find(:all, :order => sort_clause, :conditions => ???????? )

is there a better way?


Last edited by alanpieroway (2006-11-17 20:26:23)

Re: habtm filter by category

@category = Category.find(params[:id])

for exercise in @category.exercises
    puts "Exercise: #{}"

Ruby Rockstars - Ruby Jobs for all!

Re: habtm filter by category

I've tried every variation on this that I can, and can't seem to get anything. While it may seem obvious to others I 'may' smile need a bit more explanation to work with.

Although, I must say, it looks obvious - it just doesn't work for me.


Re: habtm filter by category

What jdg posted is good.
You might explain how it didn't work.

What happens when you do this?

ruby script/console
> @category = Category.find(1)
> @category.exercises

Last edited by samsm (2006-11-19 22:15:33)