One to Many Relationship Issues


I am having issues with a one to many relationship(it never works :-)).
Jokes aside, I am getting an error:

Mysql::Error: #23000Cannot add or update a child row: a foreign key
constraint fails: INSERT INTO adverts (image_url, price, title,
website_url, description, user_id) VALUES(‘bb’, 22.0, ‘aa’,’, ‘bb’, 0)

The user_id(last column) needs to be 1, and its 0

Session dump: —
flash: !ruby/hash:ActionController::Flash::FlashHash {}
:user_id: 1

class Advert < ActiveRecord::Base
belongs_to :user

class User < ActiveRecord::Base
has_many :advert

adverts controller:
def create
@advert =[:advert])
flash[:notice] = ‘Advert was successfully created.’
redirect_to :action => ‘list’
render :action => ‘new’

So its seems that the user_id is not passed into the SQL statement. Do I
need to change my create function? What needs to be added. I thought
Rails takes care of this type of plumbing…

Please help.

Here is the SQL Tables
create table users (
id int not null auto_increment,
name varchar(100) not null,
hashed_password char(40) null,
email varchar(255) not null,
city varchar(255) not null,
state varchar(255) not null,
phone varchar(255) not null,
website varchar(255) not null,
primary key (id)

create table adverts (
id int not null auto_increment,
title varchar(100) not null,
description text not null,
image_url varchar(200) not null,
price decimal(10,2) not null,
website_url varchar(255) not null,
user_id int not null,
constraint fk_adverts_users foreign key (user_id) references
primary key (id)

Try something like @user.adverts.create (params[:advert])

On 4/1/06, david [email protected] wrote:

The user_id(last column) needs to be 1, and its 0
class User < ActiveRecord::Base
render :action => ‘new’
create table users (

primary key (id)

Posted via

Rails mailing list
[email protected]

Jeremy H.

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