How to Avoid and Infinite Loop with before_save and after_save

I have an entity that looks something like this:

journal
author_first_name
author_last_name
journal_name
journal_email_address

where
journal_name = author_first_name + ' ' + author_last_name
journal_email_address = journal_name + '-' id

I had journal_name and journal_email_address implemented as attributes on the Journal model, but the time came along where, for various reasons, it has become valuable to also store that information in the database. So, what I thought I’d do, in app/models/journal.rb:
def make_journal_name
self.journal_name = self.author_first_name + ' ' + self.author_last_name
end

def make_inbound_email
self.inbound_email = self.journal_name.gsub(/[^a-zA-Z0-9]/, '') + '-' + self.id.to_s
end
def before_save
make_journal_name
make_inbound_email
end

which works fine in the case of an update of an existing record. However, it does not work in the case of a creation of a new record because before saving self.id does not exist. The result was my e-mail addresses are looking like “SallyJones-” as opposed to “SallyJones-64”.

Okay, I thought, “since I need an ID to work with I’ll move this to after_save,” like so:
def after_save
make_journal_name
make_inbound_email
self.save
end

but that creates an infinite loop.

The solution to this problem is to use an undocumented method: update_without_callbacks.
def after_save
make_journal_name
make_inbound_email
self.update_without_callbacks
end

update_without_callbacks is an instance method on ActiveRecord::Base, but for some reason it’s undocumented. In fact, it explicitly has :nodoc set in the source, although I can’t figure out why. To me, it seems that having more documented is better than having less.

The Rails Way

A big part of using Rails is understanding that if you conform to "The Rails Way" things are much easier. Of course, The Rails Way might not work for your project, and in that case, Rails might not be the right framework choice. But, you have to learn The Rails Way in order to know.

I can't claim to explain The Rails Way completely, but I've been helping a new (to Rails) developer on my team get up and running, so I've been having to coach him to see The Rails Way.

I started by talking about "entities". An entity is a thing like a "widget"...some object in our application domain that we need to represent. By convention, the names of the database table, unit tests, models, controllers, views, layouts and helpers must always coordinated in Rails to the name of the entity. So, with our "widget" entity, this is how they should be:


  • DB Table: widgets
  • Model: app/models/widget.rb
  • Controller: app/controllers/widgets_controller.rb
  • View: app/views/widget/...
  • Layout: app/views/layouts/widgets.rhtml
  • Helper: app/helpers/widgets_helper.rb

The beautiful thing about Rails is that by using generators, this gets managed for you. Here’s the approach I always take when creating an entity. This can be done through an IDE (such as RadRails, which is what I use) or on the command line...I’ll use the command line here:

  • cd path/to/rails/app
  • ruby ./script/generate model Widget which will generate your model file and your migration file with the proper table name.
  • Open up the migration, add the appropriate columns and save.
  • rake db:migrate to apply your migration to the DB.
  • ruby ./script/generate scaffold Widget which will create your controller, views, layout and helper.

Generators create a starting point to start editing, and it also gets all the file names correct. Let’s talk about the editing that needs to happen. Personally, I always do my editing in this order:

  1. Migration
  2. Model
  3. Controllers
  4. Views
  5. Layouts

This makes the most sense to me because I’m starting with the raw data, and working my way forward to what the user sees on the web page.

A little background on controllers (a good article to read is this: http://www.softiesonrails.com/search?q=rest+101): Your standard CRUD controller has 8 actions:

  • Create (Create): /widgets/create
  • Show (Read): /widgets/show/:id
  • Update (Update): /widgets/update/:id
  • Destroy (Delete): /widgets/destroy/:id
  • New (precursor to create): /widgets/new
  • Edit (precursor to update): /widgets/edit/:id
  • List (lists all entities): /widgets/list
  • Index (the default action): /widgets

When, you generate your scaffold, it’s going to automatically generate the 8 actions above. When designing entities if you have methods that don't fit within one of those actions then it's typically an indication that your entity model could our should be designed differently.

(A great example of how it's all about entity design is the login and logout actions for a User. I was thinking the other day about where the login and logout methods belong because they make sense on a User, but they aren't one of the above eight actions. Of course, I was thinking about it all wrong: login and logout are really the Create and Destroy methods on the Session entity, and Session entities belong to a User.)

Finally, a note in regard to the relationships between views, controllers and models in the context of validation. The typical user pattern in relation to creating an entity is:

  • User visits /widgets/new page
  • Enters data, click submit.
  • /widgets/new POSTs to Widgets#create
  • Widgets#create puts the data in the DB, then (if you look at the scaffold generated controller)

    • If success, calls redirect_to
    • If fails, calls render :action => :new

Why in one case does it redirect, and the other does it render? It all has to do with a little method call that should appear in your new widgets view, i.e. /widgets/new:
<%= error_messages_for 'widget' %>

See, a model has the capability to validate it’s attributes (e.g. lookup validates_presence_of in the Rails docs for examples of these capabilities). When you call Object#save the validation routines are executed and if the model doesn’t validate (i.e. Object#save returns false) we render the new action again. error_messages_for looks up the failures and automagically renders error messaging.

The beauty of generators is that script/generate scaffold Widget sets all of this up for you.

The Problem with Rails Plugins

The other day Mark asked if I was using active_scaffold. The answer is that I have a perfect use for it, and I installed it, and it works perfectly for what I need it for. However, it also overrides some core Rails functions, and when I execute functionality in my portion of the app the active_scaffold version of those functions are throwing exceptions. For example:

class ActionController::Routing::RouteSet 
def generate_with_nil_id_awareness(*args)
args[0].delete(:id) if args[0][:id].nil?
generate_without_nil_id_awareness(*args)
end
alias_method_chain :generate, :nil_id_awareness
end

Now, to me, ActionController::Routing::RouteSet seems like a pretty core function in Rails. Of course, it may be the case that I’ve done something wrong and their updated version is catching that error. (You can read more on that here: http://groups.google.com/group/activescaffold/browse_thread/thread/1c4e2f30e8b00ac6/309665c0a85d65c8).

However, my thinking is that I don’t need some plugin f’ing with my app. In fact, this points to a major issue with plugins…they’re not these self-contained units, i.e. components...but, rather, they are mixed in with the core Rails framework and our apps. This means we must think very carefully about which plugins we’ll use because, effectively, we need to know them as well as we know our own code. In other words, they are not black boxes...they are just code we import into our app that somebody else wrote (and is kind enough to share). For example, active_scaffold installs 138 files, and who knows how many kLOCs of code, and who knows what funky stuff they’ve done.

So, long story short, I’m not using active_scaffold because I don’t trust that there isn't come code in there that's gonna mess up my app, and it's too much code for me to review and become familiar with. Any ideas on an alternative?

I’ve looked at Streamlined, Hobo Scaffolding Extensions. According to the docs, Streamlined doesn’t do nested records editing which I require, Scaffolding Extensions handles nested record editing, but isn't the best UX, and Hobo has the same problem as Radiant CMS...I have to put my app into theirs, not their app into mine. (However, both Radiant and Hobo seem like nice platforms for the right project, just not the one I'm currently working on.)

What does "idiomatic Ruby" mean?

From a chat with Mark today, in regard to reading a post where I used the word "idiomatic":

(10:10:42) Mark: idiomatic, what a word
(10:11:12) Scott Porad: yes, i don't even know what it means...but people
say it when they mean, "there's a more clever way to write this in ruby".
(10:11:26) Mark: Peculiar to or characteristic of a given language.
(10:12:05) Mark: nice, one of the descriptions of idiomatic, uses idiomatic
to describe it: Characterized by proficient use of idiomatic expressions

Acts As Authenticated and Reset Password

Using Acts as Authenticated, imagine this use case:


  • User forgets password...has reset code sent to their e-mail.
  • User receives e-mail, clicks link to reset password.
  • User arrives on reset password page and thinks, "hmmm...I think I'll go visit the homepage instead".
  • User types http://www.yoursite.com/ in their browser (or clicks a link the header, or whatever).

What happens is that when the user clicks the link in the email it takes them to /account/reset_password which looks up their account by the reset code on the link (which was sent in the e-mail) and it logs them in. So, when they decide, "hmmm...I think I'll go visit the homepage instead," the user is now logged in, but has not reset their password.

To me, that seems to present a problem. So, I added a before_filter to my ApplicationController that verifies that all logged in users must have a nil password reset code otherwise they are redirected to /account/change_password. (The password reset code isn't cleared until after the user has successfully changed their password.)

In the ApplicationController I added:
before_filter :ensure_password_reset
and
module AuthenticatedSystem
def ensure_password_reset
redirect_to :controller => :account, :action => :change_password unless reset_password_has_been_changed
end

def reset_password_has_been_changed
if logged_in?
if current_user.password_reset_code.nil?
return true
else
return false
end
else
true
end
end
end

I'm certain that there is a more idiomatic Ruby way to write reset_password_has_been_changed, but I couldn't think of it.

Fixing a Blank Password Bug in Acts As Authenticated

I came across a bug in Acts As Authenticated when users tried to change their passwords. If they submitted the form with nothing in the new or confirm new password text field, then no error was thrown, but the password wasn't changed either.

The problem was in the :if clause on the validates_presence_of validation, password_required?. It was causing the validation not to occur.

    def password_required?
crypted_password.blank? || !password.blank?
end

This code is saying that a password is required in two situations:

  • when the crypted_password is blank -- that situation happens when creating a new user, OR
  • when the class instance variable 'password' is not blank -- this can only happen when the variable has been accessed, such as when attempting to update a password.

The bug is in the test for !password.blank? because it's assuming that the user will enter something as a new password. To resolve that, I changed the code to this:
    def password_required?
crypted_password.blank? || !password.nil?
end

and now the validation is called (and fails) properly. More about this issue can be found in the last few posts on this page.

How To Make the Debugger Work with RadRails

I've finally got the debugger working with Aptana's RadRails.

I've had the debugger working for awhile, but I was experiencing a problem where the current line, i.e. the current execution line, wasn't being highlighted. Actually, the source file of the current line wasn't being even opened.

After trolling around various messages boards, etc., I learned that the bug has been fixed in the latest beta version of RadRails. Here’s a post on how to do that: http://www.aptana.com/forums/viewtopic.php?t=2939

Personally, I had to manually add the update site in order to get it to work, although you might not have that experience. Of course, it took me awhile to figure out how to do this...here you go:


  • Go to Help > Software Updates > Find and Install

  • Select "Search for new features to install" and click "Next"

  • Click the button on the right for "New Remote Site"

  • Enter:

    • Name: RadRails Beta

    • URL: http://update.aptana.com/update/rails/beta/3.2/site.xml


  • Click 'OK'

  • Check the box next to "RadRails Beta"

  • Click the "Finish" button.


Now the update should download and install.

Where to put/store/save/keep your modules and files containing modules?

To a Rails newbie, sometimes the simplest things are hard to figure out. Here's what you need to know:


When you create a module, you save it to your lib/ directory.

All the modules in the lib/ directory are auto-loaded by Rails. That is, Rails does something like this:
for file in lib/
require file
end
Also, I think there is some magic to this, but I'm not 100% sure. If you have a module called MiscUtils then your file needs to be named misc_utils.rb in order for Rails to auto-load it.

Additionally, Ruby does this super-sweet thing where you can re-open any class or module and add to it at any time. In other words, you can declare a class or module in two locations, and Ruby will merge them together and treat them as one class. My experience has been that when you do this, then you need to explicitly require the files even if they're in the lib directory.

What is that hyphen right before the closing of an ERb block?

Periodically, I see some ERb code in a view like this:


<% form_tag '/posts' do -%>

<%= submit_tag 'Save' %>
<% end -%>

In fact, that code was culled right from the Rails docs at for form_tag

As you can see, in those two ERb tags, there is this syntax at close of the tag:
-%>
Today I was wondering what the hyphen (-) was for before the percentage symbol (%). It turns out that the hyphen means that when the HTML output is generated there is no line return after the close of the ERb tag.

For example, the ERb code above produces this HTML:
<form action="/posts" method="post">    <div><input name="commit" type="submit" value="Save" /></div>
</form>

whereas this ERb code:
<% form_tag '/posts' do %>    
<%= submit_tag 'Save' %>
<% end %>

produces this HTML:
<form action="/posts" method="post">
<div><input name="commit" type="submit" value="Save" /></div>
</form>

How Mixins, Include and Extend Work

I was a little puzzled tonight by this chunk of code that I found in the acts_as_authenticated plug-in module:

    def self.included(base)
base.send :helper_method, :current_user, :logged_in?
end

It comes down to some Ruby magic: when a module is included by a class the self.included method on the module is called. Likewise, when a class extends a module the self.extended method is called.

"base" is the class that includes/extends the module. "send" is calling the method ":helper_method" and passing ":current_user" and ":logged_in?" as parameters.

Special thanks to Juixe for an excellent article that helped me figure this out.

DRY Migrations (aka reverting or undoing earlier migrations)

I have a case where I made some database changes in migration 001 and now I want to undo them in migration 005. This is different that actually rolling back to version 001 (i.e. rake db:migrate version=1)...I actually want to undo or revert what I did in 001. The obvious thing to do would be to simply have 005 do the opposite of 001, but that isn't very DRY.

Using a simple example, let's say my migrations were:


  • 001_create_books.rb
  • 002_create_libraries.rb
  • 003_create_librarians.rb

and now my library is going electronic, so I do this:

  • 004_create_e_books.rb
  • 005_destroy_books.rb

In 005 I want to do the exact opposite of 001, so I did this:

class DestroyBooks < ActiveRecord::Migration
def self.up
CreateBooks::migrate(:down)
end

def self.down
CreateBooks::migrate(:up)
end
end

Custom Configurations and App Specific Settings


One not immediately obvious Ruby on Rails configuration issue I came across is how to structure application-specific config parameters, and in particular, how to make them configurable/overridable across different environments (dev, test, production). This has been solved repeatedly in different ways by the Rails community and there's info scattered around but assimilating it took a while, here's what I've settled on for now.


I couldn't have said it better myself. I've now spent 4 hours researching the best way to do this...this is a basic feature of a web app, you'd think there would be a conventional way to create ..whatever you want to call them: custom configurations, application specific settings, application configs...in Rails.

At present, I've found four solutions...the one suggested by the above blogger, and these three others:

  • http://www.taknado.com/2007/7/25/custom-configuration-info-in-rails
  • http://jarmark.org/projects/app-config/
  • Use after_initialize method on the Rails::Configuration class. (Note: this is only semi-well documented...it's documented, but not included at http://api.rubyonrails.org. I found it here: http://edgedocs.planetargon.org/classes/Rails/Configuration.html#M002860)


In addition, I found these blog posts useful:


  • http://toolmantim.com/article/2006/12/27/environments_and_the_rails_initialisation_process
  • http://glu.ttono.us/articles/2006/05/22/guide-environments-in-rails-1-1


I haven't decided how I'm going to do this yet, but I hope you find this helpful.

UPDATE: I was exchanging e-mail from Jeff at softiesonrails.com who suggested this solution:
What I usually do is add it to the bottom of environment.rb. If I have RAILS_ENV-dependent data (like development mode vs. production mode), then just put the relevant Ruby code at the bottom of environments/development.rb, for example:

    module MyConstants
ALLOWED_NAMES = ['jeff', 'cookie monster']
IP_ALLOWED = '1.2.3.4'
end

and then you can access them anywhere in your Rails code as MyConstants::ALLOWED_NAMES, etc.

If you prefer to move it to a file, you'd create a file named my_constants.rb in the /lib folder, and then explicitly require it from environment.rb:

    require 'my_constants'

Reverting Migrations (self.drop) Issue

I created an ran a migration today. Here is how my database looked to begin:


mysql> show tables;
+--------------------------------------+
| Tables_in_books_development |
+--------------------------------------+
| journals |
| schema_info |
+--------------------------------------+
2 rows in set (0.00 sec)

mysql> select * from schema_info;
+---------+
| version |
+---------+
| 19 |
+---------+
1 row in set (0.00 sec)

Then, I ran this migration:

class CreateThemes < ActiveRecord::Migration
def self.up
create_table :themes do |t|
t.column :name, :string
t.column :stylesheet_path, :string
t.column :thumbnail_path, :string
t.column :journals_count, :integer, :default => 0
end
#add_column :journals, :theme_id, :integer
end

def self.down
drop_table :themes
remove_column :journals, :theme_id
end
end

Notice how I have the add_column method commented out. Running Rake yields this:

C:\rails_apps\books>rake db:migrate
(in C:/rails_apps/books)
== CreateThemes: migrating ====================================================
-- create_table(:themes)
-> 0.1200s
== CreateThemes: migrated (0.1200s) ===========================================

As you can see, the column is not added to the journals table. Here's what my database looks like now:

mysql> show tables;
+--------------------------------------+
| Tables_in_books_development |
+--------------------------------------+
| journals |
| schema_info |
| themes |
+--------------------------------------+
3 rows in set (0.00 sec)

mysql> select * from schema_info;
+---------+
| version |
+---------+
| 20 |
+---------+
1 row in set (0.00 sec)

Well, I really need that column added to journals, so I better revert that migration via Rake, uncomment the add_column method, and re-Rake. Here's what happens:

C:\rails_apps\books>rake db:migrate version=19
(in C:/rails_apps/books)
== CreateThemes: reverting ====================================================
-- drop_table(:themes)
-> 0.0500s
-- remove_column(:journals, :theme_id)
rake aborted!
Mysql::Error: Can't DROP 'theme_id'; check that column/key exists: ALTER TABLE journals DROP `theme_id`

(See full trace by running task with --trace)

Oops! The self.down method is crapping out because there is no column in journals called theme_id. (Of course, we knew that.) Let's checkout the database now:

mysql> show tables;
+--------------------------------------+
| Tables_in_books_development |
+--------------------------------------+
| journals |
| schema_info |
+--------------------------------------+
2 rows in set (0.01 sec)

mysql> select * from schema_info;
+---------+
| version |
+---------+
| 20 |
+---------+
1 row in set (0.00 sec)

Do you see that schema_info still says version 20. I presume that the last thing a migration does is update the schema_info.version with the idea being that we don't modify the version until we sure that the migration has succeeded. The problem with that is that migrations aren't transactional--that is, they can complete or fail partially, yet the schema_info is updated as though it were a transaction. I don't know how Rails fixes this, but it's something worth knowing about.

Anyhow, at this point my database is in limbo...neither in version 19 nor 20. When I run
rake db:migrate
nothing happens because as far as Rake can tell, the DB is up-to-date. But, I can't run
rake db:migrate version=19
either because Rake will error out because there is no theme table to drop.

Okay, so the short-term solution to this problem is to clean-up the database manually. In my case, everything was actually reverted in the self.drop, but Rake doesn't know that. In your case you may have more manual clean-up to do. So, all I needed to do was update schema_info.version to 19.

Netscape Navigator 1.0

I'm not getting much work done today...my desk and office are a mess, so I'm working at cleaning up.

While doing so, I found a bit of history in my desk, and you can have it.

Create Action Requires POST

UPDATE: I wrote the whole post below, and then I figured it out...oy, the risks of auto-generated code. Typically, I use script/generate scaffold to build my controllers and views, then I start modifying from there. The risk of using auto-generated code is that you don't know every detail...and, if you're gonna own a program, you gotta know ever detail.

Long story short: I started digging around at .../verification.rb and I finally ended up back at my own controller and found this that scaffold sticks this bit of code in at the top of every controller:

# GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
verify :method => :post, :only => [ :destroy, :create, :update ],
:redirect_to => { :action => :list }

which is why I wasn't able call create with a GET. Yikes!




Boy, what a morning! I found a "feature" of Rails that I don't quite understand yet, but it certainly caused me a lot of headache. Maybe somebody else who is frustrated will benefit from this information.

Long story short: if you are going to call the create action in a controller, then you can only do so via POST. If you try to do so via GET you will get an error like the one below. In other words:

<html>
<body>
Form with POST method --> works
<form action="/books/create" method="post">
<input type="submit" name="submit" value="submit">
</form>

Form with GET method --> does not work
<form action="/books/create" method="get">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Apparently, Rails has some sort of before_filter that requires certain types of actions to be called via certain HTTP methods. (Note: I am not using any of the Rails RESTful stuff, e.g. map.resources.)

I have yet to figure out exactly what filter causes this requirement. Also, I would be interested in knowing if there is a way to inspect all the before filters that will be run for a given action or controller. If you know, please post in the comments.

Special thanks to Dirkjan for helping me debug this far.

From development.log

Processing BooksController#create (for 127.0.0.1 at 2007-09-11 10:53:22) [GET]
Session ID: e042ea5ba771fd5423d39369ec8e1227
Parameters: {"action"=>"create", "controller"=>"books", "journal_id"=>"1"}
Redirected to http://localhost:3005/books/list
Filter chain halted as [#<ActionController::Filters::ClassMethods::ProcFilter:0x47e198c @filter=#<Proc:0x0391ce4c@C:/InstantRails-1.7-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/verification.rb:74>>] returned false.
Completed in 0.01000 (100 reqs/sec) | DB: 0.00000 (0%) | 302 Found [http://localhost/books/create?journal_id=1]


Processing BooksController#list (for 127.0.0.1 at 2007-09-11 10:53:22) [GET]
Session ID: e042ea5ba771fd5423d39369ec8e1227
Parameters: {"action"=>"list", "controller"=>"books"}
Book Columns (0.010000) SHOW FIELDS FROM books
SQL (0.000000) SELECT count(*) AS count_all FROM books 
Book Load (0.000000) SELECT * FROM books LIMIT 0, 10
Rendering within layouts/books
Rendering books/list
Completed in 0.03000 (33 reqs/sec) | Rendering: 0.01000 (33%) | DB: 0.01000 (33%) | 200 OK [http://localhost/books/list]

How to use IRC for Ruby on Rails (#rubyonrails)

14 years ago I used IRC to chat with people online about the Grateful Dead and Phish, but haven't since, and basically forgot about 99% of how it works.

Then, recently I wanted to join the #rubyonrails IRC channel to get some instant information, so from http://www.rubyonrails.com/community I learned that #rubyonrails was hosted at irc.freenode.net. I downloaded ChatZilla and tried to join.

Frustration. #rubyonrails requires some sort of nickname registration and it took me the longest time to figure out how the heck it works.

I searched for documentation and found all sorts, but what I was found was very dry and technical and full of details. Typically, I like that type of stuff--bare bones, just the facts.

But, here I needed the dummies course, and I found it at http://www.zymic.com/irc.php. I can't vouch for that site, but thank goodness they had some basic info...it wasn't 100% correct, but it got me close enough.

In ChatZilla > Preferences > General there is a "nickname" setting. When you connect to irc.freenode.net you need to register this nickname...obviously, it should be something sort of unique. (How to connect? Open Firefox and visit the URL irc://irc.freenode.net ...which should launch ChatZilla.)

After ChatZilla connects to irc.freenode.net, you will need to register your nickname, aka "nick". To register the nick, type:

/msg nickserv register <yourpassword>

where <yourpassword> is some password of your creation. This will register your nickname with some sort of central registration database.

Then, to enter the channel type:

/join #rubyonrails

On subsequent visits to IRC, ChatZilla will send your username to nickserv, but you will need to "identify" yourself this time. To do so, type:

/msg nickserv identify <yourpassword>

Then, join the channel like you did before:

/join #rubyonrails

Personally, I think of it like this:


  • register = create a login
  • identify = login
  • join = enter a chat room

Hopefully, these instructions will help someone else out along the way.

P.S. By the way, the delay between posts is explained by the fact that I was out of town for a few weeks visiting family.

Incorporation

We incorporated our startup today...a small milestone on a long journey, so we took a picture to commemorate the moment.

HTML and Helpers

Look at all this code. Yikes!

Even though, in theory, you're supposed to be allowed to put HTML in your helpers, the result is that you still end up mixing up all your presentation and business logic. Some people would argue that it's not possible to separate presentation and content. I'm not arguing either way...just trying to point out that it's easy to get these things intermingled.

Anyhow, what's going on here is that a document group has a bunch of document templates. Users will have filled out some templates--in which case the "instances" of those templates become documents--and in other cases they won't have filled them out.

Originally, I was just going to do a condition based on the existence of the document or not, but then I realized this edge case that somehow a user may end up with two documents based on the same template. I'm not sure how this would happen, but could happen easily, for example, if the user bookmarked the URL for the new document page for that document template.

I suppose I could make the new action check for the existence of a document using said template for the current user, and that would almost ensure this problem wouldn't happen...from the UI. What happens if data is added directly to the database? In fact, that's how I found this case...I accidentally loaded some test data twice and my original code crapped out.

Anyhow, in my view:



    <%
    @document_group.document_templates.each do |child|
    array_of_links_to_document_if_exists_from_template(child).each do |link|
    %><li><%= link %></li><%
    end
    end
    %>


And in my helper:


def array_of_links_to_document_if_exists_from_template(document_template)
links = []
documents = Document.find(:all, :conditions => { :journal_id => @journal, :document_template_id => document_template })
if (!documents.empty?)
documents.each do |document|
links.push(link_to_remote(document.name, { :update => "dvMainPane", :url => { :controller => :documents, :action => :edit, :id => document }}))
end
else
links.push(link_to_remote(document_template.name, { :update => "dvMainPane", :url => { :controller => :documents, :action => :new, :journal_id => @journal, :document_template_id => document_template.id }}))
end
links
end

Is the helper the right place for business logic? I'm thinking right solution here isn't to put the logic in a helper...maybe helpers are really just rendering helpers...and that the logic should be in my model.

Navigating Associations in Scaffolding with Toffee

My friend Mark suggested Toffee for dealing with navigating scaffold associations.

Haven't tried it yet, but on the surface seems to solve some of what I was discussing.

Creating Multiple Objects (of different Models) in one form.

Yikes! Did I ever dig hole for myself, so let me tell you how I got out of it.

Long story short: I have a model architecture like this:

document
|
--> document_content_groups[]
|
-->document_contents

In other words, document_contents are name value pairs...think of them as questions (name) and answers (value). one or more document_contents are grouped into a document_content_group...think of that as a chunk of questions. in other words, a document_content_group has a collection of document_contents. then, a document has a collection of document_content_groups.

So, on a form where a user creates a new document really we're creating many things:

1 new document object
1 or more document_content_group objects
1 or more document_content objects

and, all of these must be associated with their parent properly.

On p. 499 the Rails book (Agile Web Development with Rails) it is suggested that something like this be done:

<% for_tag do %>
<% for @product in @products %>
<%= text_field("product[]", 'image_url') %><br />
<% end %>
<% end %>


and what this syntax is supposed to do is make the ID of the object be inserted into the form "name" field, e.g. name="product_ID[image_url]". But (sharing this is the purpose of this post), this syntax does not work with a newly created object, it only works with editing existing objects. I solved the problem like this:


@dcg_index = 0
@dc_index = 0
for document_content_group in @document_content_groups %>
<p><%= document_content_group.name %><br />
<%= text_field("document_content_group", 'name', :index => @dcg_index) %></p>
<%
for document_content in document_content_group.document_contents %>
<p><%= document_content.name %><br />
<%= hidden_field ("document_content", "document_content_group", :value => @dcg_index.to_s, :index => @dc_index) %>
<%= hidden_field ("document_content", "name", :value => document_content.name, :index => @dc_index) %>
<%= text_field("document_content", "value", :index => @dc_index) %></p>
<% @dc_index += 1%>
<% end %>
<% @dcg_index += 1%>
<% end %>


Now, the result is that when the form is posted I get two hashes in the params: document_content_groups and document_contents each of which contains hashes representing the objects I want to create.

I can easily create the document_content_groups by passing those hashes in to create, but I have to do some munging on the document_contents to prepare them:

@dcg_index = 0 # this must be the same initial index from the "new" form
for document_content_group_hash in params[:document_content_group].values do
document_content_group = @document.document_content_groups.create(document_content_group_hash)
for document_content_hash in params[:document_content].values do
if (document_content_hash["document_content_group"].to_i == @dcg_index)
# this is removed from the hash because it's not really the document_content_group_id...
# it's just a temporary ID that was used to group the items together from the _new form
document_content_hash.delete("document_content_group")
document_content_group.document_contents.create(document_content_hash)
end
end
@dcg_index += 1
end

Anyhow, not particularly pretty, but it gets the job done for now. Suggestions on how to make it more graceful are welcome.