@p-6ren">
gpt4 book ai didi

ruby-on-rails - Rails - 在 json 响应中包含关联

转载 作者:行者123 更新时间:2023-12-05 08:34:50 24 4
gpt4 key购买 nike

我有 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 => @path.questions 但是没有新的返回变量就没有办法包含问题吗?我希望我的意思很清楚。

最佳答案

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

BooksController

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

在上述情况下,Book belongs_to Author

关于ruby-on-rails - Rails - 在 json 响应中包含关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18956962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com