2013-03-26 111 views
0

可以說我擁有has_many玩具的Person。然後我有一個玩具,它有許多顏色。我想在我的Person#show方法中做的是過濾包含一系列顏色的玩具。通過has_many關聯中的屬性值範圍過濾ActiveRecord

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 

然後在我的PersonController中,我想過濾玩具是一系列的顏色。

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 

幫助或建議將不勝感激。仍然積極學習Rails。

回答

1

如果你想要去的DB方法,你可以這樣做:

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 

在顏色傳過來的PARAM如。

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