gpt4 book ai didi

ruby - 如何在 ruby​​ on rails 中创建 json 对象?

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:42 26 4
gpt4 key购买 nike

我有一个任务是在 rils 上用 ruby​​ 做 jtable。这是我的 Controller

 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>

我收到类似“与服务器通信时发生错误”的错误。添加新用户时。如何添加新学生?

最佳答案

这个新学生的 Controller 是 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

关于ruby - 如何在 ruby​​ on rails 中创建 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13598210/

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