Eager-loading an association backed by a view

Hi there,

It seems like when I am trying to eager-load an association backed by a view; it doesn’t work (SQLite or PostgreSQL, doesn’t seem to matter)

I’ve written a simple test case, and it only fails when I am trying to eager-load a view-based association.

Anything I am missing?

You could vote up this PR: Fix eager loading models without primary keys by mattalat · Pull Request #43402 · rails/rails · GitHub

You could also put self.primary_key = :post_id on your CommentView model, and see if that fixes it for you.

But I’d much rather you voted up that PR, as my teammate Matt wrote it.

Walter

Walter, I am going to look into that PR. I had this issue with pre-loading whether I had id as a primary key there at all or not (primary_key: true or primary_key: false), and it didn’t work.

However, setting self.primary_key = :post_id or even to :id (if primary_key is true) worked! So, I guess my particular issue is that ActiveRecord can’t pick up the primary key from a view (even if it is present and is called id).

Again, thanks for helping, and I think while the referenced PR is about a different issue, it deserves consideration indeed.

It depends on your DB engine, but views don’t really have primary keys in the normal sense of the word. When ActiveRecord calls DESCRIBE 'foos' to get the table details, it can’t tell which column is primary from that, and so it just doesn’t set one. Long ago, before the war, there was a final fallback in AR that said “if you can’t figure out which is the PK, and there’s a column named exactly ‘id’, then use that”. That hasn’t been true since sometime in Rails 5’s lifetime.

Walter