2012-04-25 5 views
5

모델에서 .to_json을 사용할 때 관련 모델을 조건부로 포함하는 방법을 찾으려고합니다. ActiveRecord to_json : 조건부로 연결 포함

는 단순화 된 예에서, 다음과 같은 두 가지 모델을 가정

f = Foo.find "3" 
j = f.to_json(:include => { :bars => {:some, :attributes}} 

을이 작품 :

class Foo < ActiveRecord::Base 
    has_many :bars 
end 

class Bar < ActiveRecord::Base 
    belongs_to :foo 
    attr_accessible :bar_type 
end 

내가 현재 가지고. 내가 할 수있는 방법을 찾으려면 bar_type == 'what?'을 가진 bar 인스턴스 만 포함하면됩니다.

bar 인스턴스를 조건부로 가져 오는 방법이 있거나 json 출력에 포함 된 막대를 제한하는 스코프를 사용하기를 바란다.

답변

3

뭔가를 사용하여, 당신이 할 수 있습니다 :

class Foo < ActiveRecord::Base 
    has_many :bars 
    has_many :what_bars, :class_name=>"Bar", 
         :foreign_key=>:foo_id, 
         :conditions=>"bars.bar_type = 'what'" 
end 

f = Foo.find "3" 
j = f.to_json(:include => :what_bars) 
+0

흥미로운 접근 방식을. 나는 이것을 시도하고 당신에게 돌아갈거야 :) – jaydel