LoginSignup
0
1

More than 5 years have passed since last update.

ActiveRecordのログを取るgemを作りました。

Posted at

HasLogsというActiveRecordのログを取るgemを作りました。
https://github.com/isuke/has_logs

このgemはベータ版です。バグや破壊的な仕様変更があるかもしれません。

動機

ActiveRecordのログを取るgemはauditedpaper_trailなどありますが、いずれもymlやjsonにシリアライズして保存しているので、ログの検索機能がほしいときに困りますよね。
そこで、ログテーブルにログを取るgemを作りました。

Usage

articlesというテーブルのログを取るとして、以下のようなmigrationを書きます。

class CreateAllTables < ActiveRecord::Migration
  def self.up
    create_table(:articles) do |t|
      t.timestamps
    end

    create_table(:article_logs) do |t|
      t.integer :article_id, null: false
      t.string :title, null: false
      t.text :content
      t.boolean :public, null: false, default: true
      t.datetime :created_at
    end
    add_index :article_logs,  :article_id
    add_index :article_logs, [:article_id, :created_at], unique: true
  end
end

articlesテーブルが(timestamps以外)からっぽなのがポイントです。

次にModelを以下のようにします。

class Article < ActiveRecord::Base
  has_logs
end

class ArticleLog < ActiveRecord::Base
  act_as_log
end

使って見ましょう。

article = Article.create(title: 'test1', content: 'demo1', public: false)
article.attributes =   { title: 'test2', content: 'demo2', public: false } ; article.save!
article.attributes =   { title: 'test3', content: 'demo3', public: true  } ; article.save!

article.title
=> 'test3'

article.logs
=> [#<ArticleLog id: 1, article_id: 1, title: "test1", content: "demo1", created_at: "2015-01-04 03:36:51">,
 #<ArticleLog id: 2, article_id: 1, title: "test2", content: "demo2", created_at: "2015-01-04 03:36:51">,
 #<ArticleLog id: 3, article_id: 1, title: "test3", content: "demo3", created_at: "2015-01-04 03:36:51">]

article.oldest_log
=> #<ArticleLog id: 1, article_id: 1, title: "test1", content: "demo1", created_at: "2015-01-04 03:36:51">

article.latest_log
=> #<ArticleLog id: 3, article_id: 1, title: "test3", content: "demo3", created_at: "2015-01-04 03:36:51">

article.oldest_log.next
=> #<ArticleLog id: 2, article_id: 1, title: "test2", content: "demo2", created_at: "2015-01-04 03:36:51">

article.latest_log.prev
=> #<ArticleLog id: 2, article_id: 1, title: "test2", content: "demo2", created_at: "2015-01-04 03:36:51">

いい感じです。

DB上は以下のようになっています。

articles
id title
1 title
article_logs
id article_id title content public
1 1 test1 demo1 0
2 1 test2 demo2 0
3 1 test3 demo3 1

以上です。よかったら使ってみてください。

0
1
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
0
1