ActiveRecord :include not working for belongs_to with foreign_key
-
19-09-2019 - |
Question
I have a two models set up like this:
class User < ActiveRecord::Base
# external_id column in database
end
class UserUpload < ActiveRecord::Base
belongs_to :user, :primary_key => "external_id", :foreign_key => "external_user_id"
end
However, whenever I do
upload = UserUpload.find(id, :include => :user)
The sql that gets emitted is always looking for ID (and using zeros):
select * from users where id in (0,0,0,0 ... 0,0)
Am I doing something wrong, or is there a problem using foreign_keys
in a belongs_to
relationship with include
?
Solution
I have just ran into this same problem. There's a patch that applies to Rails 2.3.5 on bug #3208 but it hasn't been applied to the 2-3-stable branch yet.
I have created a monkey patch for this bug as it is causing performance issues in my app. Place fix_belongs_to_include_with_primary_key.rb in your config/inititalizers
directory and restart your app to apply it.
OTHER TIPS
I don't know why, but option :include
in named_scope
makes belongs_to
with foreign_key
working.
named_scope :my_all, :include => :user
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow