ajax和ruby脚本只返回1条记录而不是多条记录

时间:2013-09-19 13:51:35

标签: ruby ajax postgresql sinatra

我正在使用Ruby和Sinatra进行Ajax调用。查询应返回多行,但只返回一行。

ajax脚本是:

$(document).ready(function() {
 $(".showmembers").click(function(e) {
            e.preventDefault();
            alert('script');
            var short_id =  $('#shortmembers').val();
            console.log(short_id);
            $.getJSON(
                "/show",
                 { 'id' : short_id },
                function(res, status) {
                        console.log(res);
                $('#result').html('');
                $('#result').append('<input type=checkbox value=' + res["email"] + '>');      
                $('#result').append( res["first"] );
                $('#result').append( res["last"] );
                $('#result').append( res["email"] );
                    });
        });
});

并且Ruby脚本是:

get '/show' do
id = params['id']
DB["select shortname, first, last, email from shortlists sh JOIN shortmembers sm ON sm.short_id = sh.list_id JOIN candidates ca ON ca.id = sm.candidate_id where sh.list_id = ?", id].each do |row|
    @shortname = row[:shortname]
    @first =  row[:first]
    @last = row[:last]
    @email = row[:email]
    puts @shortname
    puts @first
    puts @last
    puts @email
    halt 200, { shortname: @shortname, first: @first, last: @last, email: @email }.to_json
    end
end

如果我直接在postgres的终端上运行查询,我会返回9行但是,如上所述我的网站上只返回第一行。

有什么问题?控制台中没有错误,只有一条记录。

1 个答案:

答案 0 :(得分:0)

你的循环中有halt 200。这将导致Sinatra终止请求处理并将结果返回堆栈。

要返回完整的结果集,您需要执行以下操作:

get '/show' do
    id = params['id']

    results = DB["select shortname, first, last, email from shortlists sh 
                  JOIN shortmembers sm ON sm.short_id = sh.list_id 
                  JOIN candidates ca ON ca.id = sm.candidate_id 
                  where sh.list_id = ?", id].map do |row|
        {
            :short_name => row[:shortname],
            :first=>row[:first],
            :last=>row[:last],
            :email=>row[:email]
        }
    end

    halt 200, results.to_json       
end

这会将每行中的选定字段作为哈希数组返回。

事实上,正如我在上面看到的那样,解决方案可能就像:

一样简单
get '/show' do
    id = params['id']

    results = DB["select shortname, first, last, email from shortlists sh 
              JOIN shortmembers sm ON sm.short_id = sh.list_id 
              JOIN candidates ca ON ca.id = sm.candidate_id 
              where sh.list_id = ?", id]

    halt 200, results.to_json
end

因为除了你想要的列之外,你似乎没有选择任何东西。