Just because we aren't using ActiveRecord doesn't mean we can't have a nice API, thanks to ActiveModel we can very easily create a simple Model to encapsulate our Link object. What would such an API look like? Let's define how we would interact with a Couchbase model from our Controller.
Listing 6:
app/controllers/links_controller.rb
class LinksController < ApplicationController def create @link = Link.new(params[:link]) @link.session_id = session[:session_id] if @link.save respond_to do |format| format.html { redirect_to @link } format.js end else respond_to do |format| format.html { render :new } format.js end end end def short @link = Link.find(params[:id]) redirect_to root_path unless @link @link.views += 1 @link.save redirect_to @link.url end def show @link = Link.find(params[:id]) end def new @link = Link.new end end
So, in looking at our sketched out Controller above we can see how we would like to interact with our Link object.
We can initialize a new Link with a Hash of attributes. e.g. Link.new( params[:link] )
We can access and set a Link's attributes. e.g. @link.session_id = session[:session_id]
We can save a new Link to couchbase. e.g. @link.save
We can find and instantiate a Link object. e.g. Link.find( params[:id] )