-
Notifications
You must be signed in to change notification settings - Fork 21.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changing a model's primary_key
breaks generated SQL.
#29350
Comments
I'm having the same issue. Wondering if you've found a workaround. The # Table name: people
#
# id :integer not null
# orn :string not null, primary key
# notes :text
#
class Person < ActiveRecord::Base
self.primary_key = :orn
attr_readonly :orn
so Rails thinks it succeeded but the DB isn't updated since the |
i found a workaround for updates. maybe it will help with understanding the underlying issue: def id_in_database
self[self.class.primary_key]
end i was looking at the following source and guessing what happens next: |
Currently the methods of `AttributeMethods::PrimaryKey` are overwritten by `define_attribute_methods`. It will be broken if a table that customized primary key has non primary key id column. It should not be overwritten if a table has any primary key. Fixes rails#29350.
I was intrigued by this, as the proposed fix (#29378) changes code that has been around for a lot longer than that. I turned the new test from that PR into a repro script and bisected the failure. It started to fail at 16ae3db, when However, making the same change on master didn't fix the test. I tracked it down to b5eb321, which changed the To summarise: |
Steps to reproduce
rails new example --database=postgresql
rails g model Thing uid flag:boolean
self.primary_key = 'uid'
toapp/models/thing.rb
uid
and then attempt to update it.Expected behavior
After updating, I'd expect the value to have updated successfully.
Actual behavior
Using
rails console
, I take a Thing I've created and attempt to update it. The update appears to be successful, but once I reload my Thing instance, it becomes clear that the update didn't stick.The
flag
property returns tonil
after reloading. You can see that the call to update is trying to find the record w/["uid", "1"]
, which is the original serial id, and not the uid field I specified.This worked before I updated to Rails 5 :-(
Additionally, if I attempt to validate
uniqueness
on:uid
, then I can't evensave
existing records. ActiveRecord ends up finds the self-same record in the database and doesn't realize they're equal. However, I believe this stems from the same problem of mixing up theprimary_key
(which was set touid
) and the defaultid
.System configuration
Rails version: 5.1.1
Ruby version: 2.4.0
The text was updated successfully, but these errors were encountered: