Rails - 在json响应中包含关联

时间:2013-09-23 10:26:45

标签: ruby-on-rails rails-activerecord

我有2个表/模型:路径和问题。每个问题都属于一个路径

我的问题.rb:

class Question < ActiveRecord::Base
    belongs_to :path
end

我的路径.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 =&gt; @ path.questions但是如果没有新的返回变量,是否无法包含问题?我希望我的意思很清楚。

2 个答案:

答案 0 :(得分:1)

这非常hacky,但应该有效:

: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)

注意它还会为to_json方法添加:include选项。

答案 1 :(得分:0)

我在Rails 5 API应用程序中这样做:

BooksController

def index
  @books = Book.limit(params[:limit])
  render json: @books, include: ['author'], meta: { total: Book.count }
end

在上述情况下,图书 belongs_to 作者