0

Lets say I have Person which has_many toys. Then I have a Toy which has_many colors. What I'm trying to do in my Person#show method is filter the toys that contain a range of colors.

class Person < ActiveRecord::Base
 attr_accessible :name
 has_many :toys
end

class Toy < ActiveRecord::Base
 attr_accessible :size
 belongs_to :person
 has_many :colors
end

class Color < ActiveRecord::Base
 attr_accessible :color
 belongs_to :toy
end

Then in my PersonController I want to filter Toys be a range of colors.

class PersonController < ApplicationController
 def show
  @person = Person.find(params[:id])
  # Now I want to filter by toy colors that might be red or blue or purple or etc...
  # So when in my view I do @person.toys I know they only contain the filtered colors
  @person.toys.categories
 end
end

And help or suggestions would be greatly appreciated. Still actively learning Rails.

1 Answer 1

1

If you want to go the DB approach you could do something like:

if params[:toy_colors].nil? 
  @toys = @person.toys
else
  colors = params[:toy_colors].split(',')
  # NOTE. You should obviously check that the colors array 
  # contains only expected colors to avoid any sql injection.
  @person.toys.joins(:colors).where('colors in ?', colors)
end

where the colors are passed in as a param eg.

http://localhost:3000/person/1?toy_colors=red,green

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.