gpt4 book ai didi

jquery - 返回两个对象到Ajax请求

转载 作者:行者123 更新时间:2023-12-01 05:51:39 24 4
gpt4 key购买 nike

我正在开发一款 RESTful 民意调查应用程序,希望在一个请求中返回问题和答案。我可以在 Rails 应用程序 View 中访问这两个对象,但我的 ajax 请求只收到一个(问题)。我的想法是,我将有一个单独的应用程序来访问此投票 API。

型号:

class PollAnswer < ActiveRecord::Base
belongs_to :poll_question
end

class PollQuestion < ActiveRecord::Base
has_many :poll_answer
end

Controller :

def show
@poll_question = PollQuestion.find(params[:id])
@poll_answers = @poll_question.poll_answer

# Tried this but it didn't work
# @poll = {@poll_question.body => {:answers => @poll_answers.body}}
end

Ajax :

$.ajax({
type: "GET",
url: "http://127.0.0.1:3000/poll_questions/5.json",
success: function(html){
console.log(html);
}
});

这是返回的json:

{"id":5,"body":"What was the best scene from The Legend of Ron Burgundy","created_at":"2014-02-04T17:04:31.264Z","updated_at":"2014-02-04T17:04:31.264Z"}

最佳答案

现在您必须通过编写自定义 Controller 代码来返回它。

def show
@poll_question = PollQuestion.find(params[:id])
render json: { @poll_question.as_json({
only: [:id, :body],
include: {
poll_answers: {
only: [:body]
}
}
})
}
end

关于jquery - 返回两个对象到Ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21569811/

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