Monday, March 17, 2008

Getting started with Merb and Sequel Part 2

Continuing from my last post. My previous post is based on merb 0.5, but since then newer merb 0.9.1 is available from merbivore. There has been several changes in this release from previous version.
Ok! Now lets add another model to our application to track user status. Type this command from your application root
% merb-gen model status
This will create model named status.rb in app/models directory as well as migration file named 002_add_model_statuses.rb, Go on and edit this file to create the statuses table.
class AddModelStatuses < Sequel::Migration
def up create_table :statuses do |u|
primary_key :id
integer :user_id
varchar :status, :size => 100
text :note
datetime :time_at

def down
execute "DROP TABLE statuses"

Now that we have status table setup lets manage the user status restfully. Lets create a controller for REST enabled actions.
% merb-gen controller status
This will create a new contoller now add four actions to allow for REST protocol.
class Statuses < Application

# GET /statuses
# GET /statuses.xml
def index
@statuses = Status.filter('user_id = ?', session[:user_id])

# GET /statuses/1
# GET /statuses/1.xml
def show
@status = Status.filter('id = ?', params[:id])

# GET /statuses/new
def new


# GET /statuses/1;edit
def edit


# POST /statuses
# POST /statuses.xml
def create
Status.insert(:user_id => session[:user_id], :status => params["select_status"], :note => params["status_note"], :time_at =>

# PUT /statuses/1
# PUT /statuses/1.xml
def update
Status.filter('id = ?', params[:id]).update(:status => params["select_status"])

# DELETE /statuses/1
# DELETE /statuses/1.xml
def destroy
Status.filter(:id => params[:id]).delete

Now that we have this in controller, lets setup router.rb to use this controller restfully, Add thi s line to router.rb
r.resources :statuses
Now you can call the the statuses controller restfully from anywhere. Check out Ezra's post on Restful routes

No comments: