Saturday, March 12, 2011

Rails - Ruby: lesson in MVC

So turns out if you apply MVC correctly you save yourself from lots of unnecessary objects!

Originally I thought I needed a Board --> Panel --> Story. But as mentioned last post, using poro instead of ActiveRecord was getting 'interesting', as I had decided I didn't need any state for Board and Panel. As I was fixing tests... suddenly realized how all this was very unnecessary work:

The better solution is to create a BoardController, and then define the panels as simple attributes of that controller that reference the appropriate collection of stories:

class BoardController < ApplicationController
 def show
  @backlog = Story.find :all, :conditions => 'state IS NULL'
   respond_to do |format|
    format.html # show.html.erb
    format.xml { render :xml => @stories }
    end
  end
end

Now instead of needing to keep a bunch of keys, names in alignment between the view, board, panel objects... I just have simple associations. Each named collection I want is an attribute in the board controller, available to the view. The view simply needs to render each attribute appropriately. This approach also seem to have simplified my views, since now I just have the 'board' view, and a '_story' partial view to render each collection element.

Ruby-Rails : lessons on rails ActiveRecord vs plain old rails objects

Got distracted from doing the Agile-Web-Development-With-Rails examples, am now starting from scratch on an experiment with jquery and rails. I'm looking to see what I can achieve from a robust client app with rails based data & services via ajax.

1) Unit Tests throwing " ActiveRecord::StatementInvalid: Could not find table 'panels' "

Kept seeing this error for several basic assert statements in the model unit tests.
> assert p.is_a(Panel)
> assert p.display_text == 'backlog'

Noob mistake here... using 'rails g model' for objects that will not be stored in the database. Caused the objects to inherit from ActiveRecord class, and when ActiveRecord triggers automagic that expects a table to exist for the Panel class, and complains when it doesn't.

Instead, I really wanted to be dealing with plain old ruby objects, and viola! once I deleted the ActiveRecord reference in the model object.

> couldn't use is_a, instead had to use ruby method is_a?
> have to define the accessor methods for private instance variables.