LoginSignup
2
0

More than 3 years have passed since last update.

Railsアプリにw2uiのgridを導入した話

Last updated at Posted at 2020-03-07

やりたいこと

  • Railsアプリにw2uiのgridを導入する
  • DBからデータを取得してgridに表示させる

w2uiとは

Javascriptのライブラリです
今回はその中のGridというマスタテーブルを生成できるライブラリを使用しました

開発環境

  • Ubuntu 18.04
  • Rails 5.2
  • MariaDB

導入方法

以下3文をヘッダーに追加します

<head>
...
<link rel="stylesheet" type="text/css" href="http://w2ui.com/src/w2ui-1.5.rc1.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://w2ui.com/src/w2ui-1.5.rc1.min.js"></script>
</head>

girdを挿入したい部分にdivを追加します

<div id="grid" style="width: 100%; height: 250px;"></div>

スクリプトを記述します

<script>
  $(function () {
    $('#grid').w2grid({
      name: 'grid_name', 
      header: 'List of Tasks',
      url: {
        get: '/parent_tasks.json'
      },
      method: 'GET',
      show: {
        toolbar: true,
      },
      recid: 'id',
      limit: 10,
      columns: [
        { field: 'id', caption: 'id', size: '8%' },
        { field: 'name', caption: 'name', size: '30%' },
        { field: 'priority', caption: 'priority', size: '10%' },
        { field: 'status', caption: 'status', size: '10%' },
        { field: 'created_at', caption: 'created_at', size: '40%' }
      ],
      sortData: [
        { field: 'id', direction: 'asc' },
      ],
    });
  });
</script>
項目 概要
name gridの名前
header gridのヘッダーに表示される文言
url データをリモートから取得する際のURL
method Ajaxリクエストのメソッドを上書き
show gridに表示する項目を指定
recid recidに設定するカラムを指定
limit 取得するレコード数を指定
columns カラムを定義
sortData ソートを指定

columnsの中身

項目 概要
field フィールド名
caption 表示するカラム名
size 列幅を指定

DBからw2uiにレコードを渡す

コントローラにJSONの処理を追加します

class ParentTasksController < ApplicationController
  def index
    @task = ParentTasks.limit(10)
    respond_to do |format|
      format.html
      format.json
    end

jbuilderを追加します
表示したいデータをrecordsでくくってあげます

# index.json.jbuilder

json.records do
  json.array!(@tasks) do |task|
    json.extract! task, :id, :name, :priority, :status, :created_at
  end
end

これでサーバから取得したデータをgridで表示できるようになりました

grid.png

参考情報

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0