Skip to content
This repository has been archived by the owner on May 7, 2020. It is now read-only.

Storing Conversations in ActiveRecord

Ben edited this page Apr 3, 2016 · 6 revisions

Let's create a model that holds a conversation. We'll take advantage of the fact that most wit_bot objects can be serialized and deserialized to a hash (more details). We'll also be taking advantage of ActiveRecord::Base#serialize, which allows us to store objects as json in attribute and retrieve them from the database as the object.

Side Note:

If you're thinking that storing conversations will take up a lot of room in your database, you are correct. You'll want to destroy inactive conversations from the database every few hours. Here's the guide on setting up a job to clear old conversations with clockwork.

You can use the generator (both commands are equivalent), or do it manually with the guide.

Generator

$ rails generate wit_bot:model
$ rails generate wit_bot:model User

Guide

Create the migration...

$ rails g migration CreateConversations object:text user:references

...and the model:

class Conversation < ActiveRecord::Base
  belongs_to :user
  store :object, coder: JSON

  def object
    h = super # Get the hash from the parent method
    if h && !h.empty? # If the hash exists and is not empty,
      WitBot::Bot::Conversation::Base.from_hash h # Then create a conversation from it.
    else
      WitBot::Bot::Conversation::Base.new # Otherwise, create a new conversation.
    end
  end
  def object=(conversation)
    super conversation.as_json # Turn the conversation back into a hash.
  end
end

Great! Now we can use #object and #object= to store and retrieve conversation objects on our Conversation model. We'll also want to set up either a #has_one or #has_many relationship with the user (although it's recommended to use a #has_one to preserve state).

class User 
  has_one :conversation, dependent: :destroy
end

And you're done! Yay!

Getting Started

Here's how to get started with wit_bot in 3 steps:

  1. Learn how to use wit.ai
  2. Learn how to setup the gem
  3. Learn how to send a message

Dive Deeper

Create Bots

Integrate it

Clone this wiki locally