Hi,
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’,
‘www.drill.com/cordless’, ‘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
models:
class Advert < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :advert
end
adverts controller:
def create
@advert = Advert.new(params[:advert])
if @advert.save
flash[:notice] = ‘Advert was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
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
users(id),
primary key (id)
);