# Parent-Child Tables Help

**URL:** <https://www.ruby-forum.com/t/parent-child-tables-help/55582>\
**Category:** Rails\
**Created:** [March 22, 2006, 7:30am UTC](https://www.ruby-forum.com/t/parent-child-tables-help/55582 "2006-03-22T07:30:55Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![raydai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9d8465/32.png) [@raydai](https://www.ruby-forum.com/u/raydai)\
**Post date:** [March 22, 2006, 7:30am UTC](https://www.ruby-forum.com/t/parent-child-tables-help/55582/1 "2006-03-22T07:30:55Z")

</div>

can someone help me with this

i have a table  
cars  
(  
id int  
model\_id int  
make\_id int  
color\_id int  
description text  
constraint fk\_cars\_carmake foreign key(make\_id) references  
carmakes(id),  
constraint fk\_cars\_carmodel foreign key(model\_id) references  
carmodels(id),  
constraint fk\_cars\_color foreign key(color\_id) references colors(id)  
)

carmakes  
(  
id int  
carmake varchar  
)

carmodels  
(  
id int  
carmake\_id int  
carmodel varchar  
)

colors  
(  
id int  
color varchar  
)

Carmakes and Carmodels

- A carmake may be Toyota, Honda etc.
- A carmodel may be Corrola, Civic.
- Each carmodel will have a id of its parent.
- So for instance  
if in the carmake table i have  
1 Toyota  
2 Honda

then in the carmodel table ill have  
1 1 Corolla  
1 2 Civic  
(hope this helps you understand)

the color table is simply  
id = 1, color = red  
id = 2, color = blue …etc.

Now i want to be able to Create a form to Add Cars  
The form would have all the info pertaing to cars, along with dropdown  
lists for the makes, models, colors…

i get this error when i do it  
Mysql::Error: #23000Cannot add or update a child row: a foreign key  
constraint fails: INSERT INTO cars (`created_on`, `number_plate`,  
`price`, `title`, `updated_on`, `color_id`, `make_id`, `cc_rating`,  
`description`, `negotiable`, `views`, `year`, `transmission`, `user_id`,  
`car_type`, `mileage`, `model_id`) VALUES(’’, ‘PBO-5678’, 36000.0, ‘2001  
Corolla’, ‘2006-03-22 02:23:35’, 0, 0, 1800, ‘Nice\n’, 0, 0, 2001,  
‘Manual’, 1, ‘’’, 1600, 0)

also  
Request

Parameters: {“commit”=\>“Create”, “carmake”=\>{“id”=\>“1”},  
“color”=\>{“id”=\>“4”}, “car”=\>{“number\_plate”=\>“PBO-5678”, “title”=\>“2001  
Corolla”, “price”=\>“36000”, “cc\_rating”=\>“1800”,  
“description”=\>“Nice\n”, “negotiable”=\>“0”, “year”=\>“2001”,  
“views”=\>“0”, “transmission”=\>“Manual”, “mileage”=\>“1600”},  
“carmodel”=\>{“id”=\>“1”}}

now i think for some reason it is trying to save the other tables as  
well…not just the cars…  
anyhow i’ve been trying to get this to work for the past few nights with  
no luck…can someone help me please  
here are the controller/views.

## #Controller

class AdminController \< ApplicationController

def index

end

def return\_to\_main  
# If you have multiple scaffolds on the same view then you will want  
to change this to  
# to whatever controller/action shows all the views  
# (ex: redirect\_to :controller =\> ‘AdminConsole’, :action =\>  
‘index’)  
redirect\_to :action =\> ‘index’  
end

def list  
@cars = Car.find :all  
render :layout =\> false  
end

def new  
@car = Car.new

```
if request.xhr?
  @temp_id = Time.new.to_i
  @headers['car-id'] = @temp_id
  @headers['Content-Type'] = 'text/html; charset=utf-8'

  render :layout => false

  # If you want to send an error message:
  # render :inline => "Error text goes here", :layout => false, 

```

:status =\> 500  
end  
end

def create  
@car = Car.new(params[:car])  
@car.user\_id = session[‘user’].id  
@car.make\_id = session[‘carmake’].id  
@car.model\_id = session[‘carmodel’].id  
@car.color\_id = session[‘color’].id

```
if @car.save
  if request.xhr?
    @headers['car-id'] = @car.id
    @headers['Content-Type'] = 'text/html; charset=utf-8'
    render :partial => 'car', :layout => false, :locals => { :hidden 

```

=\> true }  
else  
return\_to\_main  
end  
else  
render :partial =\> ‘form\_errors’, :layout =\> false, :status =\> 500  
if request.xhr?  
render :action =\> ‘new’ if not request.xhr?  
end  
end

def edit  
@car = Car.find(params[:id])  
@car.user\_id = session[‘user’].id

```
render :layout => false if request.xhr?

```

end

def update  
@car = Car.find(params[:id])  
@car.user\_id = session[‘user’].id

```
if @car.update_attributes(params[:car])
  render :partial => 'car', :layout => false, :locals => { :hidden 

```

=\> true } if request.xhr?  
return\_to\_main if not request.xhr?  
else  
render :partial =\> ‘form\_errors’, :layout =\> false, :status =\> 500  
if request.xhr?  
render :action =\> ‘edit’ if not request.xhr?  
end  
end

def destroy  
Car.find(params[:id]).destroy  
render :nothing =\> true if request.xhr?  
return\_to\_main if not request.xhr?  
end  
end

## #View

 Title \<%= text\_field 'car', 'title' %\>

Make \<%= @carmakes = Carmake.find(:all, :order =\> "carmake") collection\_select(:carmake, :id, @carmakes, :id, :carmake) %\>

 Model \<%= @carmodels = Carmodel.find(:all, :order =\> "carmodel") collection\_select(:carmodel, :id, @carmodels, :id, :carmodel) %\>

 Year \<%= text\_field 'car', 'year' %\>

 Number plate \<%= text\_field 'car', 'number\_plate' %\>

 Color \<%= @colors = Color.find(:all, :order =\> "color") collection\_select(:color, :id, @colors, :id, :color) %\>

 Cc rating \<%= text\_field 'car', 'cc\_rating' %\>

 Transmission \<%= text\_field 'car', 'transmission' %\>

 Mileage \<%= text\_field 'car', 'mileage' %\>

 Price \<%= text\_field 'car', 'price' %\>

 Negotiable \<%= text\_field 'car', 'negotiable' %\>

 Description \<%= text\_area 'car', 'description' %\>

 Created on

 Updated on

 Views \<%= text\_field 'car', 'views' %\>

```
</div>

```

#--------------------------------------------------------------------------

by the way, you may ignore the user\_id, i’m using SHGL and it stores the  
user\_id fine when i tested creations before the car table had all the  
other references.

Thanks to whomsover can help me.

---

<div class="post-metadata">

**Author:** ![raydai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9d8465/32.png) [@raydai](https://www.ruby-forum.com/u/raydai)\
**Post date:** [March 23, 2006, 1:15am UTC](https://www.ruby-forum.com/t/parent-child-tables-help/55582/2 "2006-03-23T01:15:39Z")

</div>

Ray Dookie wrote:

> constraint fk\_cars\_carmake foreign key(make\_id) references  
> )  
> id int  
> 2 Honda  
> Now i want to be able to Create a form to Add Cars  
> ‘Manual’, 1, ‘’’, 1600, 0)

This ‘insert’ doesn’t match the above table definition!

You need to find out what ?\_id field isn’t in your database.  
Do you have :-  
colors.id = 0  
makes.id = 0  
models.id = 0

---

<div class="post-metadata">

**Author:** ![raydai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9d8465/32.png) [@raydai](https://www.ruby-forum.com/u/raydai)\
**Post date:** [March 23, 2006, 2:19am UTC](https://www.ruby-forum.com/t/parent-child-tables-help/55582/3 "2006-03-23T02:19:18Z")

</div>

Ray Dookie wrote:

> by the way, you may ignore the user\_id, i’m using SHGL and it stores the  
> user\_id fine when i tested creations before the car table had all the  
> other references.
> 
> Thanks to whomsover can help me.

Can you pop your models in here too?

When you assign the car make to the new car instance you should let  
rails take care of the relationships so in your model you should have;

class carmake \< ActiveRecord::Base  
has\_many :cars  
end

and in;

class car \< ActiveRecord::Base  
belongs\_to: carmake  
end

then when you add the make to the car;

@make = Carmake.find(session[:carmake])  
@make.cars \<\< @car  
@car.save

obviously a little cleaner that that & the :id needs passing in  
:carmake, but that should do it. When you save the car rails will take  
care of the foreign keys for you.

---

<div class="post-metadata">

**Author:** ![raydai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9d8465/32.png) [@raydai](https://www.ruby-forum.com/u/raydai)\
**Post date:** [March 23, 2006, 5:59am UTC](https://www.ruby-forum.com/t/parent-child-tables-help/55582/4 "2006-03-23T05:59:34Z")

</div>

Hrm… tried and still didnt not work.

ok lets try something simpler

if i have tables

* * *

car (  
id int  
name varchar  
color\_id int  
constraint fk\_cars\_color foreign key (color\_id) references colors(id)  
)

and I have a table

color(  
id int  
color\_name varchar  
)

* * *

I want a form to create cars…so on the form i would have atext-field  
for “name”  
and a dropdown list for “color”

how would the controller (create method), model and view look  
so i could just select the color from the dropdown list enter the name  
and create the car??

Thanks
