Multitable form

Hi all,

Although I’m experienced with programming I’m a beginner with ruby, RoR
and MVC

So I follow examples from books and so on and all is ok.
I can make a model who is a class and who match to a table in my
database and then I generate pretty forms on a webpage.

I would like to know how I can do to make forms who interact with more
than one table.
For an example lets imaging the 4 folling tables :

type_of_user [id, typename]

users [id, username, firsname, lastname, type_of_user_id, address_id]
where type_of_user_id is a foreign key who references the type_of_user
and where
address_id is a foreign key who references the addresses table.

addresses [id, street, number, box, zip, country_id] where
country_id …
table countries [id, countryname]

I wanna visitors to be able to register to my website so I make a pretty
form :

Username
first name
Last name
street
number
box number
zip code
country

All field are mandatory exept ‘box number’
When someone register, the type_of_user_id has 4 as value. This value is
the one of ‘standard user’.

The country has to be selected in a rolling list who contains all the
countries from the table countries.

So we can see a double interaction : We create a new adress and in the
user table we reference an id to designate this newly created address
Furthemore, in the address table there’s another interaction : The user
has choosen a country from the countries table but it’s an id who is
entered in the addresses table.

So I would like to know if it’s possible to realise such complex forms
and how… I’m also interrested to find an implementation of a similar
example or any tutorial.

Should I use the ‘view’ functionnality of mysql and make classes to
matches artificials tables ?

Thanks a lot,

STef

Stéphane Louis wrote:

For an example lets imaging the 4 folling tables :

type_of_user [id, typename]

users [id, username, firsname, lastname, type_of_user_id, address_id]
where type_of_user_id is a foreign key who references the type_of_user
and where
address_id is a foreign key who references the addresses table.

addresses [id, street, number, box, zip, country_id] where
country_id …
table countries [id, countryname]

Easy as pie:

<%= text_field ‘user’, ‘username’ %>
<%= text_field ‘user’, ‘street’ %>
<%= select ‘user’, ‘county_id’,
Country.find(:all).collect {|c| [c.id, c.name]} %>
<%= #other user fields %>

<%= text_field ‘address’, ‘street’ %>
<%= text_field ‘address’, ‘zip’ %>

Controller:

def create
@user = User.new(params[:user])
@user.address = Address.new(params[:address])
if @user.save
flash[:notice] = ‘Yay it worked!’
redirect_to :action => ‘list’
else
flash[:notice] = ‘Validation failed :(’
redirect_to :action => ‘register’
end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs