将两个对象返回给Ajax请求

时间:2014-02-05 06:07:10

标签: jquery ruby-on-rails ajax

我正在进行RESTful投票应用,并希望在一个请求中返回问题和答案。我能够在rails应用程序视图中访问这两个对象,但我只收到一个(问题)我的ajax请求。我的想法是,我会有一个单独的应用程序来点击这个民意调查api。

型号:

class PollAnswer < ActiveRecord::Base
  belongs_to :poll_question
end

class PollQuestion < ActiveRecord::Base
  has_many :poll_answer
end

控制器:

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"}

1 个答案:

答案 0 :(得分:0)

现在你必须通过编写自定义控制器代码来返回它。

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