Reputation: 45
I'm using mysql 5.5 and Rails 3.2.13. I have such table:
'CREATE TABLE `visit` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`uri` varchar(2048) COLLATE utf8_unicode_ci NOT NULL,
`remote_ip` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_agent` varchar(2048) COLLATE utf8_unicode_ci NOT NULL,
`client_id` bigint(20) DEFAULT NULL,
`position_id` bigint(20) DEFAULT NULL,
`job_posting_id` bigint(20) DEFAULT NULL,
`assessment_id` bigint(20) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idv_visit_assess_id` (`assessment_id`),
KEY `fk_visit_client` (`client_id`),
KEY `fk_visit_position` (`position_id`),
KEY `fk_visit_job_posting` (`job_posting_id`)
) ENGINE=InnoDB AUTO_INCREMENT=28649 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
And such model:
class Visit < ActiveRecord::Base
has_many :visit_actions
end
From time to time i can observe such errors in my production logs('remote_ip' was changed):
#<ActiveRecord::InvalidForeignKey: ActiveRecord::JDBCError: Cannot add or update a child row: a foreign key constraint fails (`hirex/visit`, CONSTRAINT `fk_visit_job_posting` FOREIGN KEY (`job_posting_id`) REFERENCES `job_posting` (`id`)): INSERT INTO `visit` (`assessment_id`, `client_id`, `created_at`, `job_posting_id`, `position_id`, `remote_ip`, `updated_at`, `uri`, `user_agent`) VALUES (NULL, NULL, '2013-09-13 00:25:02', 8716, NULL, '127.0.0.1', '2013-09-13 00:25:02', '/applicant/exit_job_posting', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)')>
I've spent several days trying to reproduce this issue but haven't succeed. It's Ok if i'm trying to insert null instead of real 'job_posting_id' or id of unexciting job_posting.
Any ideas?
Upvotes: 2
Views: 1665
Reputation: 44715
What is happening is that you (or someone else is trying to add job_posting_id
which doesn't exist in job_posting
table. I don't have too much code to say why this is happening, one of the most common reasons is that someone rendered a form (with job_posting
select) and before it was submitted, someone else removed given job_posting
.
Rails is very efficient in working without foreign key constraints - is there any particular reason why you enforce them?
Upvotes: 1