2013-09-23 60 views
0

我有2個表/模型:路徑和問題。每一個問題都屬於一個路徑Rails - 在json響應中包含關聯

我question.rb:

class Question < ActiveRecord::Base 
    belongs_to :path 
end 

我path.rb

class Path < ActiveRecord::Base 
    has_many :questions 
end 

一切正常,就像

p = Path.last 
Path.questions 

回報我需要的一切,但我返回像這樣的json響應:

@path = Path.find_by_id(params[:id]) 
render :status=>200, :json => {:status => "success", :path => @path, :message => "Showing path"} 

該答案不包括當然路徑的問題。我必須改變什麼以包括屬於該路徑的所有問題?我知道我可以添加:path_questions => @ path.questions,但是沒有辦法在沒有新的返回變量的情況下包含這些問題嗎?我希望這很清楚我的意思。

回答

0

這是相當哈克,但應該工作:

:path => @path.as_json.merge(:questions => @path.questions.as_json) 

最終,你可以覆蓋as_json模型裏面:

def as_json(options={}) 
    includes = [*options.delete(:include)] 
    hash = super(options) 
    includes.each do |association| 
    hash[self.class.name.underscore][association.to_s] = self.send(association).as_json 
    end 
    hash 
end 

然後只要致電::path => @path.as_json(:include => :questions)

注意它也將添加:include選項to_json方法。