В активах / javacripts
var editor;
$('document').ready(function(){
editor = new $.fn.dataTable.Editor( {
idSrc: 'id', //us "id" field for unique id
table: '#questions',
ajax: {
create: {
type: 'POST',
url: "/api/v1/questions"
},
edit: {
type: 'PATCH',
url: '/api/v1/questions/_id_'
},
remove: {
type: 'DELETE',
url: '/api/v1/questions/_id_'
}
},
fields: [
{ label: 'Final', name: 'final' },
{ label: 'Name', name: 'name' },
{ label: 'Answer A', name: 'answers.0.title' },
{ label: 'Explanation A', name: 'answers.0.explanation' },
{ label: 'id A', name: 'answers.0.id' },
{ label: 'ID', name: 'id' }
//.....
]
});
$('#questions').DataTable({
dom: 'Bfrtip',
ajax: {
"url": "/api/v1/questions",
"dataSrc": ""
},
columnDefs: [
{
targets: '_all',
defaultContent: " "
}],
columns: [
{data: "final"},
{data: "name", sortable: false},
{data: "answers.0.title", sortable: false},
{data: "answers.0.explanation", sortable: false},
{data: "answers.0.id", sortable: false, visible: false},
//.....
{data: "id", sortable: false}
],
"order": [[ 0, "asc" ],[1, "asc"]],
select: true,
buttons: [
{ extend: 'create', editor: editor },
{ extend: 'edit', editor: editor },
{ extend: 'remove', editor: editor }
]
});
//the following is for formatting the data for question_params in the controller
editor.on( 'preSubmit', function ( e, data, action ) {
if ( action === 'create' ) {
data.question = data.data[0];
delete data.data;
data.question.answers_attributes = data.question.answers;
delete data.question.answers;
}
else if ( action === 'edit' ) {
var id = Object.keys(data.data)[0];
data.question = data.data[id];
data.question.answers_attributes = data.question.answers;
delete data.data;
delete data.question.answers;
}
});
});
В html-файле
<table class="table table-striped" id="questions">
<thead>
<tr>
<th>Final?</th>
<th>Name</th>
<th>Answer A</th>
<th>Explanation A</th>
<th>id a</th>
<th>id</th>
<! ---- .......-->
</tr>
</thead>
</table>
Контроллеры / api / v1 / questions_controller
class Api::V1::QuestionsController < Api::V1::BaseController
protect_from_forgery with: :null_session
def index
#display data in JSON for editor to read
data = Question.order(:spread_sheet_number).to_json(:include => :answers)
render json: data
end
def update
question = Question.find_by(id: params.fetch(:id))
if question.update(question_params)
data = { "data" => Question.where(id: question.id).as_json(include:[:answers])}
render json: data
#...
end
end
def create
question = Question.new(question_params)
if question.save
data = { "data" => Question.where(id: question.id).as_json(include:[:answers])}
render json: data
#...
end
end
def destroy
question = Question.find(params.fetch(:id))
question.destroy
respond_with {}
end
private
def question_params
params.require(:question).permit(:name :final, answers_attributes: [:id, :title, :explanation, :_destroy])
end
end