如何在rails上的ruby中创建json对象?

时间:2012-11-28 05:07:38

标签: ruby json ruby-on-rails-3.2

我有一个任务是在rils上用ruby做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>

我遇到了一个错误,例如“与服务器通信时出错”。同时添加新用户。我怎样才能添加新学生?

2 个答案:

答案 0 :(得分: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 :(得分:1)

如果您想保存记录,则必须在表单中添加:remote => true,并且您的操作系统会在您的操作中添加以下内容:

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

如果我正确地阅读了您的问题,并且您想要在上面的代码段中的do whatever部分中仅返回您创建的最后一个用户,则可以添加:

{'Result' => 'OK','Records' => @students.last(&:attributes)}