如何在Ruby on Rails中创建JSON对象?

5

我接到了一个Ruby on Rails中做jtable任务。这是我的控制器:

 def list
    @students = Student.all
    @jtable = {'Result' => 'OK','Records' => @students.map(&:attributes)}

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @jtable}
    end
  end
def newstudent
    @student = Student.new
    @jtable = {'Result' => 'OK','Record' => @students.last(&:attributes)}
    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @jtable }
    end
  end

这是我的index.html.erb文件。
<html>
    <head>
        <%=stylesheet_link_tag "jtable_blue","http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css",:media => "all" %>
        <%= javascript_include_tag "jquery-1.8.3.min","http://code.jquery.com/ui/1.9.1/jquery-ui.js","jquery.jtable.min"%>
<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function () {
        jQuery('#StudentTableContainer').jtable({
            title: 'Table of people',
            actions: {
                listAction: '/students/list',
                createAction: '/students/new',
                updateAction: '/student/Update',
                deleteAction: '/student/Delete'
            },
            fields: {
                id: {
                    key: true,
                    create: false,
                    edit: false,
                    list: false
                },
                name: {
                    title: 'name',
                    width: '40%'
                },
                sex: {
                    title: 'sex',
                    width: '20%'
                },
                branch: {
                    title: 'branch',
                    width: '30%'
                }

            }
        });

       jQuery('#StudentTableContainer').jtable('load');
    });
</script>
</head>
<body>

    <div id="StudentTableContainer">
    </div>
</body>
</html>

当我尝试添加新用户时,出现了“与服务器通信时发生错误”的错误。请问如何添加新学生?


你能详细解释一下问题是什么吗? - macool
我编辑了我的问题。希望你能理解。 - Nithin Viswanathan
2个回答

3

这个新学生的控制器是 def newstudent。

    @student = Student.new(params.reject {|key,value| key =="controller" || key =="action"})

    if @student.save 
      @jtable = {'Result' => 'OK','Record' => @student.attributes}
    else
     @jtable = {'Result' => 'ERROR','Message'=>'Empty'}
    end  
    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @jtable }
    end

  end

1

如果您想保存记录,则必须在表单中添加:remote => true,并且您的控制器在操作中应该有类似以下内容:

if @user.save
  respond_to do |format|
    format.js # do whatever
  end
end

如果我正确理解了您的问题,并且您想在上面代码片段中的do whatever部分仅返回最后创建的用户,则可以添加以下内容:
{'Result' => 'OK','Records' => @students.last(&:attributes)}

谢谢你的帮助。我使用了这段代码,但是添加时间后出现了错误,显示为“与服务器通信时发生错误”。 - Nithin Viswanathan
1
先生,我已经找到了解决方案。 - Nithin Viswanathan
非常好,一定要接受这个答案以及你之前的问题答案,以确保在未来得到社区的帮助。 - Simpleton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接