-
Notifications
You must be signed in to change notification settings - Fork 3
Storing Conversations in ActiveRecord
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.
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.
$ rails generate wit_bot:model
$ rails generate wit_bot:model User
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!
Down here?
Cool.
I should add something somewhat interesting for you to read...
Here's how to get started with wit_bot in 3 steps:
- Learn how to use wit.ai
- Learn how to setup the gem
- Learn how to send a message
- Learn how to use message threads
- Learn how to use context
- Learn how to use conversations
- Learn to use the REPL
- Learn how to use conversations
- Learn how to use participants
- Learn how to use bots