Saturday, January 14, 2006

ROR in 14 pages

Here's a quick overview of Ruby on Rails in 14 pages.

Tuesday, January 03, 2006

Multiple Record Forms for Ruby on Rails

********************UPDATE**********************************
I have moved to a new blog location and moved my blogger posts to http://thebitt.com

I have also created a zip file of multi-record app which you can find at http://thebitt.com/2006/01/03/multiple-record-forms-for-ruby-on-rails/

**************************************************************

I have been experimenting with creating a new goal management application using Ruby on Rails. The first challenge has been creating a signup application that takes account information and account owner information and then updates both an account and an user model. I couldn't find any examples on this that I could understand so I thought I would put up a short example of a working app.

First the database - two tables Account and User

  • Account has two fields
    • id
    • name


  • User has four fields
    • id
    • first_name
    • last_name
    • account_id
The models

Account Model
class Account < ActiveRecord::Base
has_many :users
validates_presence_of :name
validates_uniqueness_of :name
validates_length_of :name, :maximum => 100
end


User Model

class User < ActiveRecord::Base
belongs_to :account
validates_presence_of :first_name, :last_name
validates_uniqueness_of :first_name
end


The view

<h1>New account</h1>
<%= start_form_tag :action => 'create' %>
<%= error_messages_for 'account' %>
<!--[form:account]-->
<p><label for="account_name">Name</label><br/>
<%= text_field 'account', 'name' %></p>
<!--[eoform:account]-->

<%= error_messages_for 'user' %>
<!--[form:user]-->
<p><label for="user_first_name">First name</label><br/>
<%= text_field 'user', 'first_name' %></p>


<p><label for="user_last_name">Last name</label><br/>
<%= text_field 'user', 'last_name' %></p>
<!--[eoform:user]-->
<%= submit_tag "Create" %>
<%= end_form_tag %>

<%= link_to 'Back', :action => 'list' %>


The controller - Signup
class SignupController < ApplicationController

model :user
model :account


def index
new
render :action => 'new'
end


def new
@account = Account.new(@params['account'])
@user= User.new(@params['yser'])
end


def create
@account = Account.new(@params['account'])
@user = User.new(@params['user'])
@account.valid?
@user.valid?
if @account.valid? && @user.valid?
name = @account.name
@account.save
@account = Account.find_by_name(name)
@account.users << @user
flash[:notice] = 'Account was successfully created.'
redirect_to :action => 'new'
else
render :action => 'new'
end
end
end


I haven't figured out how to consolidate the validation error messages - If anybody knows how please let me know.