モデルの実装
次にモデルを作成します。今回必要になるのはサーバとサーバのステータス変更履歴を表現する二つのモデルです。
通常はそれぞれでテーブルを作成しますが,
redmine_
$ ruby script/generate redmine_plugin_model ServerStatus Server name:string, status:integer, comment_counts:integer
redmine_
redmine_plugin_model <plugin_name> <model_name> [ <column_name:column_type>, ...]
なお,
モデルにリレーションや基本的なロジックを記述していきます。
app/
class Server < ActiveRecord::Base
has_many :comments, :as => :commented, :dependent => :delete_all, :order => "created_on DESC"
module Status
WORKING = 1
STOPPED = 2
end
def status_name
case self.status
when Status::WORKING
"稼働中"
when Status::STOPPED
"停止"
end
end
end
マイグレーション
次にマイグレーションと初期データを投入します。
モデルを作成した時点でPLUGIN_
mv ${PLUGIN_ROOT}/db/migrate/20100301102344_create_servers.rb ${PLUGIN_ROOT}/db/migrate/001_create_servers.rb
また,
db/
class CreateServers < ActiveRecord::Migration
def self.up
create_table :servers do |t|
t.column :name, :string
t.column :status, :integer
t.column :comments_count, :integer, :default => 0
end
(1..8).each{|i| Server.create!(:name => sprintf("server%02d", i), :status => Server::Status::WORKING)}
end
def self.down
drop_table :servers
end
end
一通りの修正が完了したらマイグレーションを実施します。
$ rake db:migrate_plugins
コントローラ・ビューの実装
さて,
まずはredmine_
$ ruby script/generate redmine_plugin_controller ServerList servers index
PLUGIN_
次にコントローラの実装です。Serverモデルからすべてのレコードを名前順に取得します。なお,
app/
class ServersController < ApplicationController
def index
@servers = Server.find(:all, :order => "name ASC")
end
end
次にビューです。@servers変数を展開してサーバ名とステータスを書き出しています。
app/
<style type="text/css">
table.servers {
width: 60%;
}
</style>
<h2>サーバ一覧</h2>
<table class="list servers"> <!-- ① -->
<thead><tr>
<th>サーバ名</th>
<th>状態</th>
</tr></thead>
<tbody>
<%- @servers.each do |server| -%>
<tr class="<%= cycle("odd", "even") %> server">
<td><%=h server.name %></td>
<td><%=h server.status_name %></td>
</tr>
<% end %>
</tbody>
</table>
①ではテーブルのclass属性にlistを指定しています。このクラスはチケットの一覧画面など,
これで準備完了です。アプリケーションサーバを再起動してブラウザをリロードしてみましょう。トップメニューに