title: ActiveRecord::InvalidForeignKey
body: <p>I'm using mysql 5.5 and Rails 3.2.13. I have such table: </p>
  
  <pre><code>'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'
  </code></pre>
  
  <p>And such model:</p>
  
  <pre><code>class Visit &lt; ActiveRecord::Base
    has_many :visit_actions
  end
  </code></pre>
  
  <p>From time to time i can observe such errors in my production logs('remote_ip' was changed):</p>
  
  <pre><code>#&lt;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)')&gt;
  </code></pre>
  
  <p>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. </p>
  
  <p>Any ideas?</p>